Sub topic 10
Promise.any: The First Fulfillment Wins
This chapter assumes you know how promises settle, how async/await works, and how Promise.race behaves. Promise.any looks a lot like race, but it treats rejections differently.
The Rule
Promise.any takes an iterable of promises and returns one promise. That promise:
- fulfills with the value of the first input to fulfill, and
- rejects only when every input has rejected.
A rejection does not end the wait. Promise.any notes it and keeps waiting for the other inputs. Promise.race works differently: it settles with whichever input settles first, whether that input fulfilled or rejected.
| Combinator | Settles when | Result |
|---|---|---|
| `Promise.race` | Any input settles | That input's value or reason |
| `Promise.any` | Any input fulfills, or all reject | First value, or an `AggregateError` |
A Fallback Across Sources
Promise.any fits the case where several sources can give the same answer and you only need one of them to work. Mirrors, replicas, and redundant caches are common examples.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
const first = await Promise.any([
failAfter(10, 'mirror A down'), // rejects first, but is ignored
delay(50, 'mirror B'), // first to fulfill
delay(100, 'mirror C')
]);
console.log(first); // 'mirror B'
}
main();Mirror A rejects after 10 ms. If you passed the same inputs to Promise.race, it would reject with "mirror A down". Promise.any waits instead, and mirror B fulfills at 50 ms. Mirror C fulfills too, at 100 ms, but by then the result is already decided, so its value is dropped.
When Every Input Rejects
If no input fulfills, Promise.any cannot pick a value. It rejects with an AggregateError, which holds every reason in input order:
async function main() {
try {
await Promise.any([
Promise.reject(new Error('A')),
Promise.reject(new Error('B'))
]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err.errors.map((e) => e.message)); // ['A', 'B']
}
}
main();The next chapter covers AggregateError in detail. For now, remember that a catch around Promise.any receives a wrapper object, not the first reason.
Common Mistakes
- Treating
anyas a fasterrace. If a quick failure should stop the wait, as in a timeout, userace.Promise.anyignores a timeout's rejection and keeps waiting. - Reading
err.messageand nothing else. The message on anAggregateErroris generic. The useful details are inerr.errors. - Expecting the losers to stop. Slower inputs keep running after a winner is picked. A later chapter shows how to cancel them with
AbortController. - Older runtimes.
Promise.anyarrived in ES2021, in Node 15 and recent browsers. Check your target environments before relying on it.
Exercise
Promise.any([failAfter(20, 'x'), delay(30, 'y'), failAfter(5, 'z')]) is awaited. What happens, and what would Promise.race do with the same inputs?
Show answer
Promise.any fulfills with 'y' at about 30 ms, because both rejections are skipped. Promise.race rejects at about 5 ms with the Error 'z', because that input settles first.
Exercise
Every source passed to Promise.any rejects. How do you log each individual failure message?
Show answer
Catch the rejection, which is an AggregateError, and loop over err.errors, for example err.errors.forEach((e) => console.log(e.message)). The reasons come in input order.