如何解决承诺早日回报-带有承诺的地图阵列
我们有以下代码可以发表ajax帖子并下载多个文件。
诺言不必等待其他人完成,而应全部异步完成。
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(在downloadFile api调用中调用)。
如何更改上述内容,以便仅在所有先前的发帖请求完成后才调用当await downloadAllFiles
时的finally。
解决方法
您需要在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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。