我该怎么做才能使以下`.then()`只触发一次?

时间:2018-06-13 06:07:04

标签: javascript loops promise

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

  // 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()内的代码运行了两次。

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

1 个答案:

答案 0 :(得分:2)

使用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))