Home > Web Front-end > JS Tutorial > Does Promise.all Guarantee the Order of Resolved Values Matches the Input Iterable Order?

Does Promise.all Guarantee the Order of Resolved Values Matches the Input Iterable Order?

Barbara Streisand
Release: 2024-11-03 14:41:31
Original
623 people have browsed it

Does Promise.all Guarantee the Order of Resolved Values Matches the Input Iterable Order?

Preserving Order in Promise.all

Promise.all is a JavaScript function that takes an iterable of promises and returns a single promise that resolves once all the input promises have resolved. It's often used to wait for multiple async operations to complete before proceeding.

A common question arises: is the order of the resolved values in the output promise guaranteed to match the order of the input promises?

According to the MDN documentation, it appears that the values passed to the then() callback of Promise.all are presented in the order of the promises. This question seeks confirmation from the spec.

The Promise.all spec (https://tc39.github.io/ecma262/#sec-promise.all) states that:

  • Promise.all(iterable) takes an iterable as input and iterates over it using IteratorStep(iterator).
  • Each resolved promise has an internal [[Index]] slot, which indicates its index in the original iterable.
  • Resolving is implemented via Promise.all() Resolve, where the resolved promise's [[Index]] slot is used to determine the index of the value in the output array.

Combining these points, it's clear that the output of Promise.all will always strictly follow the order of the input iterable. This means that if you pass an array to Promise.all, the resolved values will appear in the output array in the same order as they appeared in the input array.

To demonstrate this, consider the following example:

<code class="javascript">const promises = [1, 2, 3, 4, 5].map(Promise.resolve);
Promise.all(promises).then((results) => {
  console.log(results); // [1, 2, 3, 4, 5]
});</code>
Copy after login

In this case, the output will be [1, 2, 3, 4, 5], regardless of which promise resolves first.

The above is the detailed content of Does Promise.all Guarantee the Order of Resolved Values Matches the Input Iterable Order?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template