Promise.any(iterable) accepts an iterable of promises and resolves as soon as one of them fulfills, returning that value. It rejects with an AggregateError only when every supplied promise rejects. An empty iterable causes an immediate AggregateError whose .errors array is empty. Promises passed to Promise.any start executing immediately and are not canceled when one fulfills; use AbortController when cancellation is required. Common use cases include querying multiple endpoints and taking the first successful response or trying multiple browser APIs and using the first available. fetch() only rejects on network errors or CORS violations, so HTTP errors must be handled manually.
Promises have long been our go-to when working with asynchronous code in JavaScript. If you've used Promise.all() or Promise.race() to coordinate async operations, you know the patterns. But what if you're only interested in the first successful result, ignoring failures? That's exactly what Promise.any() does: it fulfills with the first resolved promise and ignores any that reject (unless all reject).
How it works Promise.any(iterable) Takes an iterable of promises. Resolves as soon as one fulfills. Rejects with an AggregateError if all reject. An empty iterable rejects immediately with an AggregateError whose .errors array is empty. Promises passed to Promise.any() are already running. It doesn't cancel the rest when one succeeds. Use AbortController if cancellation is important.
Everyday scenarios Fallback APIs Imagine you're querying multiple third-party endpoints. You only care about the first one that works: const fetchWithCheck = (url) => fetch(url) .then(response => { if (!response.ok) { throw new Error(`HTTP error: ${response.status}`); } return response; }); Promise.any([ fetchWithCheck('https://mirror1.example.com/data'), fetchWithCheck('https://mirror2.example.com/data'), fetchWithCheck('https://mirror3.example.com/data') ]) .then(response => response.json()) .then(data => { console.log('Got data from the first responsive server:', data); }) .catch(error => { if (error instanceof AggregateError) { console.error('All servers failed:', error.errors); } else { console.error('Unexpected error:', error); } }); ⚠️ Note: fetch() only rejects on network errors (such as being offline) or CORS policy violations, which appear as generic network failures.
Collection
[
|
...
]