Home > Article > Web Front-end > Does `Promise.all` Preserve the Order of Resolved Values?
Promise.all: Order of Resolved Values
In JavaScript, Promise.all is designed to enhance the functionality of promises by allowing the resolution of multiple promises concurrently. One key aspect of Promise.all is the order in which resolved values are passed to its callback.
According to the MDN documentation, the order of resolved values should correspond to the order of the promises in the input array. This means that the first promise to resolve will have its value placed first in the results array passed to the then() callback.
To confirm this, let's delve into the JavaScript Promise specification. Within the section "Promise.all (iterable)," we find the steps for resolving an iterable of promises into a single Promise. The crucial detail lies in step 4e, which involves creating an internal [[Index]] slot for each resolved promise. This slot explicitly marks the index of the promise in the original input array.
Therefore, the Promise.all implementation ensures that when resolving multiple promises concurrently, the output is strictly ordered based on the order of promises in the input array. This order preservation holds true as long as the input array maintains a consistent ordering (for example, an array).
To illustrate this, consider the following code:
<code class="js">const somePromises = [1, 2, 3, 4, 5].map(Promise.resolve); Promise.all(somePromises).then(function(results) { console.log(results); // Expected result: [1, 2, 3, 4, 5] });</code>
When this code is executed, the resolved values will be logged to the console in the order of the promises in the somePromises array. This demonstrates the order preservation feature of Promise.all.
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!