promise.all 在 forEach 循环中——所有的东西都同时触发 [英] promise.all inside a forEach loop — everything firing at once

查看:23
本文介绍了promise.all 在 forEach 循环中——所有的东西都同时触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Node 应用程序中,我需要以同步方式迭代一些项目,但循环内的一些操作是异步的.我的代码现在看起来像这样:

In a Node app, I need to iterate through some items in a synchronous fashion, but some of the operations inside the loop are asynchronous. My code right now looks like so:

someAPIpromise().then((items) => {
   items.forEach((item) => {
      Promise.all[myPromiseA(item), myPromiseB(item)]).then(() => {
         doSomethingSynchronouslyThatTakesAWhile();
      });
    }
}

items 是一个 1 的数组时,这会产生奇迹.但是,一旦有多个项目,promise.all() 将立即触发每个数组中的项,无需等待循环中的操作结束.

This works wonders when the items is an array of 1. But, once there's more than one item, promise.all() will just fire off instantly for every item in the array, without waiting for the operation in the loop to end.

说了这么多...我怎样才能确保数组中每一项的整个操作都是同步运行的(即使有些操作是异步的并返回一个承诺)?

All that to say... how can I ensure that the entire operation for each item in the array is run synchronously (even if some operations are async and return a promise)?

非常感谢!

N

推荐答案

好吧……我们能够让它工作的方式:array.reduce() 在 Promise 的帮助下.最终结果:

All righty... the way we were able to get it to work: array.reduce() with the help of Promises. The end result:

myAsyncAPIcall.then(items => {
    items.reduce((current, nextItem) => {
        return current.then(() => {
          return new Promise(res => {
             Promise.all([myPromiseA(nextItem), myPromiseB(nextItem]).then(() => {
               someSynchronousCallThatTakesAWhile(nextItem);
               res();
             }).catch(err => {
                   console.log(err);
             });
          });
        });
    }, Promise.resolve())
})

它的工作方式是将数组的每个项目包装在自己的Promise(resolve, reject),我们可以保证每次迭代都是同步运行的,因为一次迭代完成会触发需要解析下一个Promise,以此类推.在每个 promise 解析中,调用可以根据需要异步启动,并且知道它们在完成之前只会被限制在父 promise 内.

The way it works is, by wrapping each item of the array in its own Promise(resolve, reject), we can ensure that each iteration is run synchronously, as the completion of one iteration will trigger the need to resolve the next Promise, and so on and so forth. Within each promise resolving, calls can get kicked off asynchronously as much as you want, with the knowledge that they will only be scoped to the parent promise until it finishes.

希望对大家有所帮助!

这篇关于promise.all 在 forEach 循环中——所有的东西都同时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆