Promise.any()
Promise.any() is a static method that takes an iterable of promises and returns a single Promise that resolves as soon as any one of the input promises resolves. Unlike Promise.race(), which settles as soon as any promise settles (whether resolved or rejected), Promise.any() waits for the first successful resolution.
If all input promises reject, Promise.any() rejects with an AggregateError, which contains an array of all the rejection reasons.
Syntax
Promise.any(iterable)
Parameters
- iterable
- An iterable (such as an Array) of promises or other values to check.
Return Value
A Promise that:
- Resolves as soon as any promise in the iterable resolves (with that promise’s value)
- Rejects with an
AggregateErrorif all promises in the iterable reject
Description
Promise.any() is useful when you want the first successful result from multiple independent async operations. Think of it as an “OR” operation for promises — you care about the first win, and you don’t care which one wins.
This method is the logical counterpart to Promise.all(), which waits for all promises to resolve, and Promise.race(), which settles with the first promise to settle (success or failure).
AggregateError
When all promises reject, the returned promise rejects with an AggregateError object. This error has two key properties:
errors— an array containing all the rejection reasonsmessage— a string describing that all promises were rejected
Examples
First successful resolution
const p1 = new Promise((resolve, reject) => {
setTimeout(() => reject('first failure'), 100);
});
const p2 = new Promise((resolve) => {
setTimeout(() => resolve('second success'), 50);
});
const p3 = new Promise((resolve) => {
setTimeout(() => resolve('third success'), 75);
});
Promise.any([p1, p2, p3])
.then((value) => {
console.log(value); // Output: "second success"
});
Handling AggregateError
const p1 = Promise.reject('Error 1');
const p2 = Promise.reject('Error 2');
const p3 = Promise.reject('Error 3');
Promise.any([p1, p2, p3])
.catch((aggregateError) => {
console.log(aggregateError.errors);
// Output: ["Error 1", "Error 2", "Error 3"]
});
See Also
Promise.all()— Waits for all promises to resolvePromise.race()— Settles as soon as any promise settlesPromise— The Promise global object