【发布时间】: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。 -
顺便说一句,尽量避免混淆
then和await语法。
标签: javascript node.js promise es6-promise