When making multiple requests concurrently with Promise.allSettled
, does the order of the array in the response correspond to the intitial array in the request? Does it maintain the same order regardless of the order in which they settle?
const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 2000, 1)); //finish last
const promise2 = Promise.resolve(2); //finish first
const promise3 = new Promise((resolve, reject) => setTimeout(resolve, 100, 3)); //finish in the middle
const promises = [promise1, promise2, promise3];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result)));
In testing it seems to be true, but there seems to be no guarantee in the documentation that the order will remain. The MDN docs are here
The Promise.allSettled() method takes an iterable of promises as input and returns a single Promise . This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.
Yes, the values in results are in the same order as the promises .
Promise.all() will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise.allSettled() will wait for all input promises to complete, regardless of whether or not one rejects. Use allSettled() if you need the final result of every promise in the input iterable.
It returns a single Promise that resolves when all of the promises passed as an iterable, which have resolved or when the iterable contains no promises.
Yes, it is guaranteed. The steps are described in the specification.
On each iteration over the passed iterable, it does
Set resolveElement.[[Index]] to index. Set rejectElement.[[Index]] to index.
where index
is the current index in the iterable being iterated over, which then gets passed to the resolver or rejector algorithm. Both the resolver and the rejector does, at the end:
Set values[index] to obj.
where values
is the array of resolve values that the whole Promise.allSettled
will resolve with.
The nth item in the passed iterable/array will always correspond to the nth item in the resolved array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With