首页 > 解决方案 > 承诺数组两种不同的行为

问题描述

我有一个产生一系列承诺的代码:

    async addDefect(payload) {
    this.newDefect.setNote(payload.note);
    this.newDefect.setPriority(payload.priority);
    const name = await this.storage.get(StorageKeys.NAME);
    const movingFilesJob = this.cachedPhotoUrls.map(url => {
      const defectImage = this.newDefect.generateImageUrl(name);
      return this.file.moveImageToAppFile(url, defectImage.url);
    });
    await Promise.all(movingFilesJob);
    this.viewCtrl.dismiss(this.newDefect);
  }

现在我想将创建转移movingFilesFob到另一个班级。我写了以下函数:

async persistPhotos(photoBuffer: string[], defect: Defect) {
    const name = await this.storage.get(StorageKeys.NAME);
    return photoBuffer.map(url => {
      const defectImage = defect.generateImageUrl(name);
      return this.file.moveImageToAppFile(url, defectImage.url);
    });
  }

但是当我尝试替换代码时,我收到以下错误:

'Promise[]>' 类型的参数不可分配给'Iterable<{} 类型的参数 | PromiseLike<{}>>'。“Promise[]>”类型中缺少属性“[Symbol.iterator]”

我正在调用新函数,如下所示:

async addDefect(payload) {
    this.newDefect.setNote(payload.note);
    this.newDefect.setPriority(payload.priority);
    const name = await this.storage.get(StorageKeys.NAME);
    const movingFilesJob = this.photo.persistPhotos(this.cachedPhotoUrls, this.newDefect);
    await Promise.all(movingFilesJob);
    this.viewCtrl.dismiss(this.newDefect);
  }

为什么第一个示例中的相同代码有效,但在以下示例中却没有。我可以选择 type :any 来返回,但它无论如何都不能在运行时工作。

标签: javascriptangulartypescript

解决方案


Promise.all在函数内部移动

async persistPhotos(photoBuffer: string[], defect: Defect) {
    const name = await this.storage.get(StorageKeys.NAME);
    return Promise.all(photoBuffer.map(url => {
      const defectImage = defect.generateImageUrl(name);
      return this.file.moveImageToAppFile(url, defectImage.url);
    }));
  }

Async函数总是返回一个 Promise。现在你正在返回一个 Promise 数组。因为这个函数的结果是一个返回 Promise 数组的 Promise:

const results = await persistPhotos(...);

现在results将包含 Promises 数组。如果你想得到他们的结果,你必须:

const realResults = await Promise.all(results);

或者,您可以Promise.all在函数内部移动。


推荐阅读