Promise.any(iterable) fulfils with the first promise to fulfil and ignores rejections, unless every input rejects. Then it rejects with an AggregateError whose .errors holds all the reasons in input order. An empty input rejects straight away, and plain values count as already fulfilled. Contrast the family: all fails fast on the first rejection, allSettled never rejects, race settles with whichever settles first, success or failure, and any waits for a success. Implementing it means counting rejections by index and calling resolve from every input. The first call wins, because a promise settles only once.
Know Promise.any from memory.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Every input's fulfilment goes straight to resolve, and only the first call matters. Rejections are stored by index and counted. When the count reaches the length, reject with AggregateError(errors). Promise.resolve(p) lets plain values and thenables in. An empty array has nothing that could fulfil, so it rejects immediately.
// The first promise to fulfil wins. If every one rejects, reject with an AggregateError// holding all the reasons, in input order.function promiseAny(promises) {return new Promise((resolve, reject) => {if (promises.length === 0) {reject(new AggregateError([], 'All promises were rejected'));return;}const errors = new Array(promises.length);let rejected = 0;promises.forEach((p, i) => {Promise.resolve(p).then(resolve, (error) => {errors[i] = error; // by index, not arrival orderif (++rejected === promises.length) reject(new AggregateError(errors, 'All promises were rejected'));});});});}
passes 4 checks run on every build, against the native method where there is one
- the first fulfilment wins, even after rejections
- all rejected: AggregateError with reasons in input order
- an empty array rejects
- plain values count as fulfilled
Iterate with for...of, so Sets and generators work, and count while iterating, because the length isn't known up front. No input can be counted before the loop ends, because then handlers always run later as microtasks, even for promises that are already settled. So the count is final when the first rejection arrives. An iterator that throws rejects the result. The first check compares the outcome with native Promise.any on 150 random schedules of fulfilments, rejections and plain values.
// Like the built-in: any iterable, plain values count as fulfilled, and an iterator that// throws rejects the result.function promiseAny(iterable) {return new Promise((resolve, reject) => {const errors = [];let count = 0;let rejected = 0;try {for (const item of iterable) {const i = count++;errors.push(undefined);Promise.resolve(item).then(resolve, (error) => {errors[i] = error;// Handlers run as microtasks, after this loop has finished, so count is final here.if (++rejected === count) reject(new AggregateError(errors, 'All promises were rejected'));});}} catch (error) {reject(error);return;}if (count === 0) reject(new AggregateError([], 'All promises were rejected'));});}
passes 4 checks run on every build, against the native method where there is one
- same outcome as native Promise.any on 150 random schedules
- any iterable: a Set, a generator
- an iterator that throws rejects with its error
- an already-settled rejection still waits for the loop to finish
Promise.any can't stop the requests that lose. Pass each task an AbortSignal from one controller, and abort it when the race ends either way, so slower mirrors stop downloading. The caller's own signal rejects at once and cancels everything. Tasks start inside then(), so a task that throws synchronously counts as a rejection instead of escaping.
// Promise.any can't stop the losers. With tasks that accept an AbortSignal, the winner can:// first success cancels the rest; the caller's signal cancels everything.function firstFulfilled(tasks, { signal } = {}) {return new Promise((resolve, reject) => {const controller = new AbortController();const finish = (settle) => (value) => {controller.abort(new DOMException('Another task finished first', 'AbortError'));signal?.removeEventListener('abort', onAbort);settle(value);};const onAbort = () => finish(reject)(signal.reason);if (signal?.aborted) return onAbort();signal?.addEventListener('abort', onAbort, { once: true });// Start each task in a then(), so a task that throws synchronously counts as a rejection.const runs = tasks.map((task) => Promise.resolve().then(() => task(controller.signal)));Promise.any(runs).then(finish(resolve), finish(reject));});}
passes 4 checks run on every build, against the native method where there is one
- the first success cancels the others
- all fail: AggregateError, errors in task order
- the caller's abort rejects and cancels every task
- an already-aborted signal never starts a task
Fastest mirror or CDN
Request the same resource from several endpoints and use whichever answers first successfully; a failing mirror shouldn't fail the whole load, which is exactly any rather than race.
Cache or network
Service workers can try the cache and the network together and serve the first that succeeds.
AggregateError
AggregateError was added with Promise.any to report several failures at once; its errors property keeps each reason.
Confusing
anywithrace:racesettles on the first rejection too.Storing errors in arrival order instead of input order.
Resolving an empty input instead of rejecting it.
Expecting
anyto cancel the losing promises (it can't; pass a signal).Rejecting with a plain array instead of an
AggregateError.
What do all, allSettled, race and any each settle on?
all: every fulfilment, or the first rejection. allSettled: every settlement, never rejects. race: the first settlement of either kind. any: the first fulfilment, or every rejection.
How would you get the fastest success with a timeout?
Promise.any([...requests]) raced against a timer, or better, give every task AbortSignal.timeout(ms) so they also stop.
Why does an empty input reject?
Nothing can ever fulfil, and "all inputs rejected" is vacuously true, so the spec rejects with an empty AggregateError.