Home > Web Front-end > JS Tutorial > Does `Promise.all()` Preserve the Order of Resolved Values?

Does `Promise.all()` Preserve the Order of Resolved Values?

DDD
Release: 2024-11-04 05:22:29
Original
1002 people have browsed it

Does `Promise.all()` Preserve the Order of Resolved Values?

Promise.all: Preserving Order of Resolved Values

The Promise.all() method takes an iterable as its argument and returns a new promise that resolves once all the promises in the iterable have resolved. The question arises: is the order of the resolved values guaranteed to match the order of the promises in the iterable?

According to the MDN documentation, the resolved values should appear in the order of the promises. However, a direct reference to this specific behavior is not immediately apparent in the spec.

Delving deeper into the specification, we find that PerformPromiseAll() is invoked with the iterable passed to Promise.all(). PerformPromiseAll() then iterates over the iterable using IteratorStep(), which guarantees the order of promises.

Moreover, each resolved promise has an internal [[Index]] slot that denotes its index in the original input iterable. This slot is used during the resolution process to ensure that the output array maintains the original order.

In summary, the order of resolved values in Promise.all() is strictly preserved as long as the input iterable is ordered. This is exemplified in the following code snippet:

<code class="js">const slow = new Promise(resolve => setTimeout(resolve, 200, 'slow'));
const instant = 'instant';
const quick = new Promise(resolve => setTimeout(resolve, 50, 'quick'));

Promise.all([slow, instant, quick]).then(responses => {
  responses.map(response => console.log(response));
});

// Output: [ 'instant', 'quick', 'slow' ]</code>
Copy after login

The above is the detailed content of Does `Promise.all()` Preserve the Order of Resolved Values?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template