【问题标题】:What can I do to make the following `.then()` to only trigger once?我该怎么做才能使以下`.then()`只触发一次?
【发布时间】:2018-11-22 14:44:47
【问题描述】:

在下面的代码中。我正在为formFields 的属性运行一个循环。如您所见,我使用计数器仅在使用api.uploadFieldFile 上传所有文件时才运行this.updatePanoCollection()

  // formFields = { logo: { file: ... }, thumbnail: { file: ... } }

  let toUploadCount = 0
  let uploadedCount = 0

  Object.entries(formFields).forEach(([key, upload]) => {
    if (!upload || !upload.file) return
    toUploadCount++
    api.uploadFieldFile('logo', upload.file).then(downloadUrl => {
      formFields[key] = downloadUrl
      const updatePayload = {
        id: this.currentPanoCollection.id,
        data: formFields
      }
      uploadedCount++
      if (toUploadCount === uploadedCount) {
        // This only runs once right now
        return this.updatePanoCollection(updatePayload)
      }
    }).then(() => {
      // But this runs twice. It should only run once.
    }).catch(err => this.handleError(err))
  })

现在的问题是.then() 中的代码运行了两次。

如何更改此代码使其仅运行一次(在所有文件上传后)?

【问题讨论】:

  • 你指的是哪个then 你只想运行一次,第一次还是第二次?可能想要Promise.all
  • @CertainPerformance 第二个。
  • @MaazSyedAdeeb 我不确定是否应该使用promise.all。我只回报一个承诺。当文件尚未上传时,promise 不会返回。

标签: javascript loops promise


【解决方案1】:

使用Promise.all 而不必维护完成计数,如下所示:

Promise.all(
  Object.entries(formFields).map(([key, upload]) => {
    if (!upload || !upload.file) return;
    return api.uploadFieldFile('logo', upload.file)
      .then(downloadUrl => {
      formFields[key] = downloadUrl
    })
  })
)
  .then(() => {
    // all have been uploaded
    const updatePayload = {
      id: this.currentPanoCollection.id,
      data: formFields
    }
    return this.updatePanoCollection(updatePayload);
  })
  .then(() => {
    // update is completed as well
  })
  .catch(err => this.handleError(err))

【讨论】:

  • 非常感谢。有用!我很少使用Promise.allPromise.all 如何记录上传次数?例如,它如何知道有 1 次或 2 次上传?
  • 它只会等待数组中的所有Promises 传递给解析,然后再自行解析。因此,例如,如果有 [<Promise>, undefined],那么它将忽略 undefined 并等待单个 Promise
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多