Parallel or Sequential: The Nature of Promise.All() in Node.js
A question arises regarding the execution process of Promise.all() in Node.js. Does it handle promises sequentially or concurrently?
Q1: Sequential or Parallel Processing?
The documentation leaves room for ambiguity, so let's clarify: Promise.all(iterable) does not execute all promises sequentially like a chain of promises (e.g., p1.then(p2).then(p3)...) nor does it run them all in parallel. Rather, it awaits the resolution of multiple promises.
Q2: Achieving Sequential Execution
If Promise.all() lacks sequential capabilities, is there an alternative?
For an existing set of promises, there's no native way to enforce sequential execution. However, if you have an iterable of asynchronous functions, you can create a sequential execution chain using Array::reduce:
iterable.reduce((p, fn) => p.then(fn), Promise.resolve())
The above is the detailed content of ## Does Promise.all() Execute Promises Sequentially or in Parallel?. For more information, please follow other related articles on the PHP Chinese website!