Home >Web Front-end >JS Tutorial >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:
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>
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!