Promise.any
Returns the first successful result and skips errors.
Available since: ES2021
Syntax
Promise.any(promises)Parameters
| Parameter | Type | Description |
|---|---|---|
| promises | Iterable | An array of promises. |
Return value
PromiseA promise with the first successful result, or an AggregateError if all reject.
Examples
The first successful answer:
const result = await Promise.any([
Promise.reject(new Error('Mirror 1 down')),
new Promise((resolve) => setTimeout(() => resolve('Mirror 2'), 50)),
new Promise((resolve) => setTimeout(() => resolve('Mirror 3'), 100)),
]);
console.log(result);Output:
Mirror 2Notes
Unlike Promise.race(), an error does not end the wait. Only if every promise rejects is an AggregateError thrown, with the list in its errors property.
See also
- Promise.race — Returns the result of the first promise to settle — successful or not.
- AggregateError — Several errors in one — thrown by Promise.any.
- Promise.all — Waits for all promises in parallel.
In the tutorial
- Several promises at once — Promise.all, Promise.allSettled, Promise.race and Promise.any in JavaScript: how to wait for several asynchronous actions at the same time.