Sub topic 10
Promise.any: The First Fulfillment Wins
This chapter assumes you already know async/await, try/catch, and the earlier chapters on Promise.all and Promise.race. Promise.any is the combinator for "I need one good answer, and I don't care which source gives it." You hand it several promises. It fulfills as soon as any one of them fulfills, and it ignores rejections along the way.
Promise.any is part of ES2021. It is available in Node.js 15+ and in all current browsers.
The Settlement Rules
Promise.any follows the shared combinator model: an iterable goes in and one promise comes out. Its rules for settling that promise are:
- When any input fulfills, the returned promise fulfills with that input's value. Later results are ignored.
- When an input rejects,
Promise.anyrecords the reason and keeps waiting. - It rejects only when every input has rejected. The rejection reason is an
AggregateErrorthat holds all the individual reasons. The next chapter covers that error in detail.
This is the mirror image of Promise.all. Promise.all stops at the first rejection and needs every input to fulfill. Promise.any stops at the first fulfillment and needs every input to reject before it fails.
A First Example: Several Mirrors
Suppose the same file is hosted on three mirrors. One is down, one is slow, and one is fast. The helpers below simulate those cases with timers.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
const winner = await Promise.any([
fail(10, 'mirror A down'),
delay(80, 'mirror B'),
delay(50, 'mirror C')
]);
console.log(winner); // 'mirror C'
}
main();Here is the timeline. Mirror A rejects at 10 ms, and Promise.any notes the error and carries on. Mirror C fulfills at 50 ms, and the returned promise fulfills with 'mirror C'. Mirror B finishes at 80 ms, but by then the result has already been decided, so its value is dropped.
"First" means first in time, not first in the input array. Mirror C wins even though it is listed last.
How It Differs from Promise.race
Promise.race and Promise.any both pick a single winner, so they are easy to mix up. The difference lies in what counts as winning. race takes the first input to settle, and a rejection counts. any takes the first input to fulfill.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
const inputs = () => [fail(10, 'fast failure'), delay(50, 'slow success')];
try {
console.log('race:', await Promise.race(inputs()));
} catch (err) {
console.log('race rejected:', err.message); // race rejected: fast failure
}
console.log('any:', await Promise.any(inputs())); // any: slow success
}
main();The function inputs() builds fresh promises for each call, so the two combinators get identical, independent starting conditions.
| Question | `Promise.race` | `Promise.any` |
|---|---|---|
| What settles the result? | First input to settle, either way | First input to fulfill |
| Does an early rejection end it? | Yes | No, it is recorded |
| When does it reject? | When the first settler rejects | Only when all inputs reject |
| Rejection reason | That input's reason | `AggregateError` with every reason |
| Typical use | Timeouts, "whatever happens first" | Fallbacks, redundant sources |
Use race when a failure should stop you. Use any when a failure only means "try the next source."
Ties and Already-Settled Inputs
When several inputs have already fulfilled before Promise.any looks at them, the earliest one in input order wins:
async function main() {
const value = await Promise.any([
Promise.resolve('first'),
Promise.resolve('second')
]);
console.log(value); // 'first'
}
main();Internally, Promise.any subscribes to each input in order with .then. When the inputs are already fulfilled, their reactions run as microtasks in that same order. The first reaction fulfills the result, and the remaining ones have no effect.
Plain values are treated the same way. Each input passes through Promise.resolve, so a non-promise value counts as an input that is already fulfilled:
async function main() {
const value = await Promise.any([Promise.reject(new Error('nope')), 42]);
console.log(value); // 42
}
main();The edge-cases chapter later covers empty iterables, where Promise.any behaves differently from the other combinators.
Gotchas
A "successful" promise might not be the success you want
Promise.any only knows whether a promise fulfilled. It has no idea whether the result is useful to you. The classic trap is fetch. It fulfills for any HTTP response, including 404 and 500, and it rejects only on network failure. If you pass raw fetch calls to Promise.any, a fast 500 error page beats a slower 200 response.
The fix is to convert unwanted results into rejections before they reach the combinator:
async function fetchFromAnyMirror(urls) {
return Promise.any(
urls.map((url) =>
fetch(url).then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);
return res;
})
)
);
}
async function main() {
try {
const res = await fetchFromAnyMirror([
'https://example.com/missing-file',
'https://example.com/'
]);
console.log('Got', res.url, res.status);
} catch (err) {
console.log('All mirrors failed:', err.errors.map((e) => e.message));
}
}
main();This needs Node.js 18+ (for global fetch) and network access. The same idea applies to any API that reports failure through a fulfilled value, such as { ok: false } objects or empty results. Validate the value inside each input, and throw when it is not acceptable.
Total failure waits for the slowest input
Promise.any can't reject until every input has rejected. If five sources fail quickly and a sixth hangs for 30 seconds before failing, your caller waits 30 seconds to learn that everything failed. If an input never settles, a total failure never gets reported at all. When that matters, put a deadline around the call with the timeout pattern from the Promise.race chapter:
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}
async function main() {
try {
await withTimeout(
Promise.any([fail(10, 'A'), fail(5000, 'B')]),
200
);
} catch (err) {
console.log(err.message); // Timed out after 200 ms
}
}
main();A process running this still lives for about 5 seconds, because the timer inside fail(5000, 'B') keeps running. That leads to the next gotcha.
The losers keep running
Once Promise.any fulfills, the other inputs are not stopped. Their network requests, timers, and computations carry on, and their results are thrown away. With redundant requests, that means bandwidth and server load you no longer need. The later chapter on cancellation shows how to abort the remaining requests with an AbortController.
Rejections are handled, not lost
Every input you pass in gets a rejection handler from Promise.any, so rejected inputs don't trigger "unhandled rejection" warnings. Only the returned promise needs a catch or a try/catch around its await. If every input rejects and you leave that out, the AggregateError itself becomes the unhandled rejection.
When to Reach for Promise.any
Use Promise.any when you have several interchangeable ways to get the same result:
- Redundant endpoints or CDN mirrors, where you take the fastest healthy one.
- Several cache layers or lookup strategies, where any hit is good enough.
- Feature detection across alternatives, where the first one that loads is used.
Avoid it when you need every result (use Promise.all or Promise.allSettled), or when a failure should stop the whole operation right away (use Promise.race or Promise.all).
Exercise
What does this log, and roughly when? await Promise.any([fail(30, 'X'), delay(100, 'slow'), fail(60, 'Y')]) using the delay and fail helpers from this chapter.
Show answer
It logs 'slow' at about 100 ms. The rejections at 30 ms and 60 ms are recorded and ignored, because an input is still pending. When the 100 ms promise fulfills, Promise.any fulfills with its value.
Exercise
You replace Promise.race with Promise.any in a function that races a fetch against a timeout promise that rejects after 2 seconds. What changes?
Show answer
The timeout stops working as a timeout. Promise.any ignores the timeout's rejection and keeps waiting for the fetch. If the fetch is slow, the result arrives late. If the fetch also rejects, you get an AggregateError holding both reasons instead of a timeout error. Timeouts need Promise.race, because there a rejection has to end the wait.
Exercise
Promise.any([fetch(primaryUrl), fetch(backupUrl)]) returns a response with status 503 even though the backup is healthy. Why, and how do you fix it?
Show answer
fetch fulfills for every HTTP response, error statuses included, so the primary's fast 503 counts as a fulfillment and wins. Chain .then((res) => { if (!res.ok) throw new Error(HTTP ${res.status}); return res; }) onto each fetch so error statuses become rejections. Then Promise.any skips them.