Что я могу сделать, чтобы следующий `.then ()` срабатывал только один раз? - PullRequest
0 голосов
/ 13 июня 2018

В следующем коде.Я запускаю цикл для свойств 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 голосов
/ 13 июня 2018

Используйте 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))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...