在for循环中等待承诺

时间:2017-07-31 07:59:53

标签: node.js promise async-await

如何迭代一堆项目并执行一些异步任务并等待它们全部?

for (const item of items) {
    Promise.all([item.someAsync1, item.someAsync2]]).then(res => {
        const [res1, res2] = res;
        doSomeSyncStuffWithRes1AndRes2();
    }).catch(err => console.log(err));
}
console.log('finished'); //I want this to print only after everything has finished.

我已经尝试创建一系列承诺并将所有内容推送到它,但这也不起作用,因为我在每次迭代中消耗了承诺?

2 个答案:

答案 0 :(得分:-2)

好吧,我想我明白了:

const promises = [];
for(const item of items) {
    promises.push(this.handleItem(item)); //handle item is the inside of each iteration
}
return Promise.all(promises);

答案 1 :(得分:-2)

所以项目是一系列具有承诺的对象?

您需要登录一个promise回调,并对整个项目集合执行另一个promise.all,如下所示:

Promise.all(items.map(item => 
   Promise.all([item.1async,item.2async])
   .then(completedAsyncItems => doSomething()))
.then(allCompletedItems => console.log())