promise.all inside a forEach loop — everything firing at once

前端 未结 5 1963
暗喜
暗喜 2020-12-03 12:38

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:

5条回答
  •  孤城傲影
    2020-12-03 13:30

    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())
    })
    

    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.

    I hope this helps folks!

提交回复
热议问题