ES2020 - Promise.any
Promise.any() is a method that gets resolved when at least one of the given
Promises gets resolved.
It gets as an argument an iterable of
Promise objects and returns a single
Promise that resolves with value of that very
const result = await Promise.any([ Promise.resolve(33), new Promise(resolve => setTimeout(() => resolve(66), 1000)), Promise.reject(new Error('an error')) ]); // result = 33;
result here is equal with
33 since this is the result of the very first
Promise that manages to get resolved.
The key difference with
Promise.race is that
Promise.race returns the value of the very first resolved or rejected
Promise.any cares only about the very first resolved (successful) one.
When all given
Promise objects get rejected, then
Promise.any rejects and returns the errors. These might be in one of the following format:
- an array containing all the rejection errors of each
- an AggregateError object, which is an object representing an error when several errors need to be wrapped in a single error
This is something that is not finalized yet so
Promise.any is still in stage 3.
This method can become handy when we are happy to move on when at least one
Promise resolves and we don't really care about the rest of them. Cheers!!