How to Use Promise.any in JavaScript: Syntax and Examples
Promise.any to wait for the first promise that fulfills among multiple promises. It returns a new promise that resolves with the value of the first fulfilled promise or rejects if all promises reject.Syntax
The Promise.any method takes an iterable of promises and returns a new promise. This new promise resolves as soon as any input promise fulfills, with the value of that promise. If all input promises reject, it rejects with an AggregateError containing all rejection reasons.
Promise.any(iterable): iterable is an array or any iterable of promises.- Returns a promise that fulfills with the first fulfilled value.
- Rejects with
AggregateErrorif all promises reject.
Promise.any([promise1, promise2, promise3])Example
This example shows three promises: two reject and one fulfills after a delay. Promise.any resolves with the first fulfilled promise's value.
const p1 = new Promise((_, reject) => setTimeout(() => reject('Error 1'), 100)); const p2 = new Promise((resolve) => setTimeout(() => resolve('Success 2'), 200)); const p3 = new Promise((_, reject) => setTimeout(() => reject('Error 3'), 300)); Promise.any([p1, p2, p3]) .then(value => console.log('First fulfilled:', value)) .catch(error => console.log('All promises rejected:', error.errors));
Common Pitfalls
1. Confusing Promise.any with Promise.race: Promise.race resolves or rejects as soon as any promise settles (fulfills or rejects), while Promise.any waits for the first fulfillment only.
2. Handling rejection: If all promises reject, Promise.any rejects with an AggregateError, which contains all rejection reasons in its errors property.
3. Not catching errors: Always add a .catch to handle the case when all promises reject.
const p1 = Promise.reject('Fail 1'); const p2 = Promise.reject('Fail 2'); // Wrong: no catch, will cause unhandled rejection Promise.any([p1, p2]) .then(value => console.log(value)); // Right: catch the AggregateError Promise.any([p1, p2]) .then(value => console.log(value)) .catch(error => console.log('All failed:', error.errors));
Quick Reference
| Feature | Description |
|---|---|
| Input | An iterable (like an array) of promises |
| Resolves | With the first fulfilled promise's value |
| Rejects | With AggregateError if all promises reject |
| Error type | AggregateError with errors array |
| Difference from Promise.race | Promise.any ignores rejected promises until one fulfills |