Skip to content

Promise.any(): first success wins (ES2021)

  • What Promise.any() fulfills with, and when it rejects with an AggregateError.
  • How it differs from Promise.race(), which also settles early.
  • How to query redundant sources and cancel the slower ones once one succeeds.
  • The edge cases: empty input, plain values, non-iterables, and AggregateError.errors.

TL;DR: Promise.any(iterable) returns a promise that fulfills with the value of the first input to fulfill. Rejections are ignored unless every input rejects; then it rejects with an AggregateError whose errors array holds every rejection reason, in input order.

It was added in ECMAScript 2021 together with AggregateError, and is supported by every current browser and server runtime (details in Compatibility).

Sometimes several interchangeable sources can answer and one answer is enough: CDN mirrors, read replicas, a cache plus the network. Before ES2021 there was no built-in “first success” combinator:

  • Promise.all waits for everything and fails as soon as one input fails: the opposite of what you want.
  • Promise.race settles with the first input to settle, so a fast failure beats a slower success.

Running the samples: the samples on this page are ES modules with top-level await. Save one as a .mjs file and run it with Node.js 22 (node sample.mjs). The outputs shown were produced with Node.js 22.23.

In this example the OrdersPortal app can load its price list from three mirrors. The US mirror fails first:

const wait = (ms, value, fail = false) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
// Three mirrors serve the same OrdersPortal price list. Any one is enough.
const priceList = await Promise.any([
wait(40, 'eu mirror'),
wait(10, 'us mirror timed out', true),
wait(25, 'asia mirror'),
]);
console.log('loaded from:', priceList);
// Promise.race settles with the first input to settle, even if it is a failure.
try {
await Promise.race([
wait(40, 'eu mirror'),
wait(10, 'us mirror timed out', true),
wait(25, 'asia mirror'),
]);
} catch (error) {
console.log('race rejected:', error.message);
}

Output:

loaded from: asia mirror
race rejected: us mirror timed out

Promise.any skipped the failure; Promise.race gave up on it. Before ES2021, developers emulated any by inverting Promise.all (swapping fulfillment and rejection on every input and on the result), which was hard to read.

// Fragment: signature
const value = await Promise.any(iterable);
// fulfills with the first fulfilled value,
// or rejects with AggregateError { errors: [reason0, reason1, ...] }
  • Input is any iterable. Each element goes through Promise.resolve(), so plain values and thenables work. A plain value counts as an immediate fulfillment.
  • Fulfillment: the first input to fulfill wins. Later fulfillments and rejections are ignored.
  • Rejection: only after every input has rejected. The AggregateError has an errors array in input order (not rejection order), holding the original reasons unchanged.
  • Empty input: there is nothing that can fulfill, so the result rejects at once with an AggregateError whose errors is []. This differs from Promise.all([]) and Promise.allSettled([]), which fulfill with [], and Promise.race([]), which stays pending forever.
  • A non-iterable argument rejects the returned promise with a TypeError.
try {
await Promise.any([
Promise.reject(new Error('eu mirror: HTTP 503')),
Promise.reject(new Error('us mirror: timed out')),
]);
} catch (error) {
console.log(error instanceof AggregateError); // true
console.log(error.name, '-', error.message);
console.log(error.errors.map((e) => e.message));
}
try {
await Promise.any([]);
} catch (error) {
console.log('empty:', error.name, error.errors);
}
console.log(await Promise.any([Promise.reject(new Error('x')), 42]));
try {
await Promise.any(123);
} catch (error) {
console.log(error.constructor.name);
}

Output:

true
AggregateError - All promises were rejected
[ 'eu mirror: HTTP 503', 'us mirror: timed out' ]
empty: AggregateError []
42
TypeError

The message All promises were rejected is V8’s wording; other engines use different text, so never match on it. Check instanceof AggregateError and read errors instead.

In the specification (PerformPromiseAny), each rejection is stored at its input’s index and the AggregateError is created only when the last input rejects. Its errors property is non-enumerable, so JSON.stringify(aggregateError) prints {}.

OrdersPortal fetches its price list from whichever of three mirrors answers first. Three details make it production-ready:

  1. fetch rejects only on network failures, so HTTP errors are turned into rejections; otherwise a fast 503 would “win”.
  2. Once one mirror succeeds, the others are cancelled with an AbortController; Promise.any does not stop them on its own.
  3. AbortSignal.timeout() bounds the whole attempt, and an all-mirrors failure is rethrown as one readable error with the AggregateError kept as its cause.
// price-list.mjs - load the OrdersPortal price list from whichever mirror answers first.
const MIRRORS = [
'https://eu.cdn.example.test/prices.json',
'https://us.cdn.example.test/prices.json',
'https://asia.cdn.example.test/prices.json',
];
async function getJson(url, signal) {
const response = await fetch(url, { signal });
// fetch rejects only on network errors; turn HTTP errors into rejections.
if (!response.ok) throw new Error(`${new URL(url).hostname}: HTTP ${response.status}`);
return response.json();
}
export async function loadPriceList({ timeoutMs = 2000 } = {}) {
const losers = new AbortController(); // cancels the slower mirrors once one succeeds
const signal = AbortSignal.any([losers.signal, AbortSignal.timeout(timeoutMs)]);
try {
return await Promise.any(MIRRORS.map((url) => getJson(url, signal)));
} catch (error) {
if (error instanceof AggregateError) {
const reasons = error.errors.map((e) => (e instanceof Error ? e.message : String(e)));
throw new Error(`All price-list mirrors failed (${reasons.join('; ')})`, { cause: error });
}
throw error;
} finally {
losers.abort(); // harmless if every request has already settled
}
}
// --- Demo: a mocked fetch. Each mirror has [delay in ms, HTTP status].
let plan;
const log = [];
globalThis.fetch = (url, { signal }) =>
new Promise((resolve, reject) => {
const host = new URL(url).hostname;
const [delay, status] = plan[host];
const onAbort = () => {
clearTimeout(timer);
log.push(`aborted ${host}`);
reject(signal.reason);
};
const timer = setTimeout(() => {
signal.removeEventListener('abort', onAbort);
log.push(`done ${host}`);
resolve({ ok: status === 200, status, json: async () => ({ source: host, currency: 'USD' }) });
}, delay);
signal.addEventListener('abort', onAbort);
});
plan = { 'eu.cdn.example.test': [10, 503], 'us.cdn.example.test': [500, 200], 'asia.cdn.example.test': [30, 200] };
console.log(await loadPriceList());
console.log(log);
plan = { 'eu.cdn.example.test': [10, 503], 'us.cdn.example.test': [20, 500], 'asia.cdn.example.test': [5000, 200] };
try {
await loadPriceList({ timeoutMs: 100 });
} catch (error) {
console.log(error.message);
console.log(error.cause instanceof AggregateError, error.cause.errors.length);
}

Output:

{ source: 'asia.cdn.example.test', currency: 'USD' }
[
'done eu.cdn.example.test',
'done asia.cdn.example.test',
'aborted us.cdn.example.test'
]
All price-list mirrors failed (eu.cdn.example.test: HTTP 503; us.cdn.example.test: HTTP 500; The operation was aborted due to timeout)
true 3

In the first run the EU 503 is ignored, Asia wins after 30 ms, and the slow US request is aborted. In the second run every mirror fails (the last by timeout), and the caller gets one error that still carries all three reasons. The finally block aborts the losers on every path (see Promise.finally for the promise form).

  • Using Promise.race for “first success”. race settles with the first input to settle, including a fast failure. Use any when only success counts.
  • Letting HTTP errors “win”. fetch fulfills for a 404 or 503. Without an ok check, the fastest error response is the result.
  • Forgetting the losers. Promise.any stops waiting; it does not stop the other requests. Pass an AbortSignal and abort it once you have a winner, or redundant requests double your backend load.
  • Logging only the AggregateError message. Log error.errors, which holds the real reasons.
  • Assuming any([]) waits or fulfills. It rejects immediately; guard against an empty source list.
  • No timeout. If one input never settles and the others reject, any never settles. Bound it with AbortSignal.timeout().
  • Hedging non-idempotent work. Sending the same POST /orders to two endpoints and taking the first success can create two orders. Use any for reads or idempotent operations only.
Combinator Settles when Fulfills with Rejects when
Promise.all (ES2015) all fulfill, or the first rejects array of values the first input rejects
Promise.allSettled (ES2020) every input has settled array of { status, value | reason } in practice, only for a bad iterable
Promise.any (ES2021) the first fulfills, or all reject the first fulfilled value every input rejects (AggregateError)
Promise.race (ES2015) the first input settles that value the first input to settle rejects

Use Promise.any when inputs are redundant and one success is enough: mirrors, replicas, fallback providers, or “cache or network, whichever succeeds first”. Choose something else when:

  • You need every result. Use Promise.all, or Promise.allSettled for partial results.
  • You need a deadline that can fail the operation. Promise.race against a timer (or an AbortSignal.timeout()) expresses “answer or error by time T”.
  • Sources have a preference order. Try the primary first and fall back sequentially; any treats all inputs as equal.

According to MDN’s browser compatibility data, Promise.any and AggregateError are supported in Chrome 85, Edge 85, Firefox 79, Safari 14 (including iOS), Node.js 15.0.0, Deno 1.2 and Bun 1.0. Internet Explorer never supported them. The realistic example also uses AbortSignal.any(), which needs Node.js 20.3+ or a current browser.

TypeScript: Promise.any and AggregateError are declared in lib.es2021.promise.d.ts. Add es2021 or later to lib if a project pins an older one. AggregateError.errors is typed any[], so treat each entry as unknown and check it. For older runtimes, use a maintained polyfill such as core-js; TypeScript does not polyfill runtime methods.

1. What is the difference between Promise.any and Promise.race? race settles with whichever input settles first, fulfilled or rejected. any ignores rejections and fulfills with the first input that fulfills; it rejects only when all inputs reject.

2. What does Promise.any reject with, and why not just the last error? An AggregateError whose errors array holds every rejection reason in input order. When every source failed, each reason may be different (a timeout here, a 503 there), and you need all of them to diagnose the outage.

3. What does Promise.any([]) do? It rejects immediately with an AggregateError whose errors is empty, because no input can ever fulfill. Promise.all([]) and Promise.allSettled([]) fulfill with [], and Promise.race([]) never settles.

4. Senior scenario: tail latency on a read API is high, and someone proposes sending each request to two replicas with Promise.any. What do you check and how do you build it? First, that the operation is idempotent; never hedge writes. Second, cost: duplicating every request doubles load, so prefer a hedged request: send to the primary, and only if it has not answered within about its p95 latency, also send to a second replica and take Promise.any of the two. Turn HTTP errors into rejections, share an AbortController so the loser is cancelled once one wins, bound the whole call with AbortSignal.timeout(), and on total failure log every entry in AggregateError.errors. Measure that the hedge actually cuts p99 without overloading the replicas.

  • Promise.any (ES2021) fulfills with the first successful input and rejects with an AggregateError only when every input fails.
  • Unlike Promise.race, a fast failure does not win.
  • any([]) rejects immediately; AggregateError.errors lists the reasons in input order.
  • It never cancels the slower inputs or adds a timeout; use an AbortController and AbortSignal.timeout().
  • Use it for redundant, idempotent reads; use all or allSettled when you need every result.