【问题标题】:Waiting for promises in a for loop在 for 循环中等待 Promise
【发布时间】:2018-01-06 16:44:51
【问题描述】:

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

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.

我尝试过创建一组承诺并将所有内容推送给它,但这也不起作用,因为我在每次迭代中都在使用承诺?

【问题讨论】:

  • jquerys when 方法合适吗?
  • 不,如果有帮助的话,我正在使用带有异步等待支持的纯 nodejs(expressjs 应用程序)。
  • 呃,在promise前面加个await
  • item.someAsync1 到底是什么?这是一个在调用时返回承诺的函数吗?或者一个已经被调用的函数的承诺本身?

标签: node.js promise async-await


【解决方案1】:

好的,我想我明白了:

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

【讨论】:

    【解决方案2】:

    所以 items 是一个包含 promise 的对象数组?

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

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

    【讨论】:

      猜你喜欢
      • 2018-06-09
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 2023-01-20
      • 2019-05-22
      相关资源
      最近更新 更多