【问题标题】:Promise returns early - Map array with promisesPromise 提前返回 - 带有 Promise 的映射数组
【发布时间】:2020-09-30 17:12:36
【问题描述】:

我们有以下代码,它可以创建一个 ajax 帖子并下载多个文件。

promise 不必等待其他人完成,应该全部异步完成。

async function downloadAllFiles(fileIds, token) {
  var promises = fileIds.map(async fileId => {
    return await downloadIndividualFile(fileId, token);
  });
  Promise.all(promises).then(res => {
    return res;
  });
}

async function downloadIndividualFile(fileId, token) {
  return await downloadFile(fileId, token) // makes call to API post etc.
    .then(async result => {
      // handle the file download result
      // save file
    })
    .catch(error => {
      console.log(error);
    });
}

然后从不同的文件中调用它:

await downloadAllFiles(fileIds, token)
      .then(res => {
        console.log('result from download all');
        console.log(res);
      })
      .catch(error => {
        console.log(error);
      })
      .finally(() => {
        console.log('finally');
      });

当前发生的是 finally 在 post promise 实际完成之前被调用(在 downloadFile api 调用中调用)。

如何更改上述内容,以便在调用 await downloadAllFiles 时,仅在所有先前的发布请求都完成时才调用 finally。

【问题讨论】:

  • downloadAllFiles 没有返回任何内容?
  • Promise.all(promises).then(…) 缺少 return
  • 顺便说一句,尽量避免混淆 thenawait 语法。

标签: javascript node.js promise es6-promise


【解决方案1】:

您需要在downloadAllFiles 函数中返回承诺。更新:

return Promise.all(promises).then(res => {
    return res;
});

对您的代码进行一些重构

function downloadAllFiles(fileIds, token) {
  var promises = fileIds.map(fileId => return downloadIndividualFile(fileId, token));
  return Promise.all(promises);
}

async function downloadIndividualFile(fileId, token) {
  try {
    const result = await downloadFile(fileId, token);
    // handle the file download result
    // save file
  } catch (error) {
      console.log(error);
  }
}

downloadAllFiles(fileIds, token)
  .then(res => {
    console.log('result from download all');
    console.log(res);
  })
  .catch(error => {
    console.log(error);
  })
  .finally(() => {
     console.log('finally');
  });

如果您使用.then,则不需要await

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多