Choosing Between Promise.all, Promise.any, and Promise.allSettled
Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment
Prompt
You are building a backend gateway that fans out concurrent requests across multiple upstream services in JavaScript. Evaluate the language's three primary promise concurrency combinators—Promise.all, Promise.any, and Promise.allSettled—across mechanics, lifecycle pitfalls, and service-orchestration patterns:
- Five-Way Behavioral Matrix: Contrast the three combinators across (a) when the outer promise fulfills, (b) when it rejects and what value/error it rejects with, (c) the shape of the resolved payload, (d) whether outputs follow input position or completion order, and (e) what happens when given an empty iterable such as
[]. - Short-Circuiting, Cancellation, and Error Handling: Clarify what happens to still-running promises and open network sockets when
Promise.allfails early orPromise.anyfinds a winner, how each combinator retains or discards sibling errors, and how to prevent unhandled-rejection crashes when one concurrent operation fails before another is awaited. - Matching Combinators to Production Patterns: Pick and justify the right combinator for each of these three gateway workflows:
- Analytics Overview Screen: Fetching 4 independent report cards (revenue chart, active sessions, support queue, deployment log) where every healthy card must render even if a sibling card fails with an inline fallback state.
- Pre-Commit Order Authorization: Running risk scoring, stock eligibility, and credit-limit verification in parallel before capturing payment, aborting the checkout immediately if any single check denies or errors.
- Multi-Edge Key Bundle Fetch: Requesting an immutable public-key manifest from 4 regional edge replicas, proceeding as soon as the earliest valid payload arrives.
Scope & Expectations
- Exact specification semantics: Cover settlement rules,
AggregateErrorstructure, input-index ordering vs. first-winner resolution, and vacuous-truth vs. zero-candidate behavior on[]. - Runtime lifecycle & I/O control: Distinguish JavaScript promise short-circuiting from actual socket cancellation (
AbortController) and show why sequentialawaiton pre-started promises triggers unhandled rejections. - Production-ready scenario mapping: Pair each gateway use case with the right combinator plus essential HTTP safeguards (
!res.okchecks, body-read timing, timeouts, and cooperative cancellation).
Step-by-step walkthrough
How JavaScript promise combinators work under the hood
A JavaScript
Promiseis a placeholder for the result of an asynchronous operation: it startspendingand permanently settles once into eitherfulfilled(with avalue) orrejected(with an errorreason). A concurrency combinator takes an iterable of inputs—usually promises representing concurrent API calls—and returns one single combinedPromise.Before comparing
Promise.all,Promise.any, andPromise.allSettled, note three foundational rules they all share:- Non-promise values are wrapped automatically: Each element is passed through
Promise.resolve(element), so mixing plain values like42withfetch(...)calls works seamlessly. - Every input is watched immediately: All three combinators synchronously attach internal fulfillment and rejection handlers to every input promise during the call. If one input rejects after the combined promise has already settled, the combinator's internal handler absorbs it—preventing spurious "UnhandledPromiseRejection" crashes.
- Callbacks always run on a microtask: Even if the combined promise settles immediately (such as on an empty array
[]), any.then(...)or.catch(...)callback you attach runs asynchronously on the microtask queue (the high-priority callback queue drained right after the current synchronous JavaScript turn finishes).
- Non-promise values are wrapped automatically: Each element is passed through
Compare all, any, and allSettled across the five dimensions
Dimension Promise.all(iterable)Promise.any(iterable)Promise.allSettled(iterable)Fulfillment Condition Fulfills when every input fulfills. Fulfills as soon as the first input fulfills. Fulfills once every input settles (fulfilled or rejected). Rejection Condition & Value Rejects immediately when the first input rejects, with that single rejection reason.Rejects only when every input rejects, with an AggregateErrorwhose.errorsarray holds all rejection reasons.Never rejects due to input rejections (only rejects if iterating the argument itself throws, e.g., passing null).Result Structure Array of fulfilled values: [v0, v1, ...].Single fulfilled value vfrom the winning promise.Array of outcome objects: { status: "fulfilled", value }or{ status: "rejected", reason }.Result Ordering Preserves input iterable order ( results[i]matchesinputs[i]).Returns whichever input fulfilled first in time (on total failure, err.errors[i]preserves input order).Preserves input iterable order ( results[i]matchesinputs[i]).Empty Iterable ( [])Returns an already-fulfilled promise with [].Returns an already-rejected promise with AggregateError(errors: []).Returns an already-fulfilled promise with [].Here
AggregateErroris a standard JavaScriptErrorsubclass designed to bundle multiple failures into one error object via its.errorsarray property.Trace all three on the same three concurrent upstream calls: -
p1: fulfills with"Profile"at240 ms-p2: rejects withError("502")at80 ms-p3: fulfills with"Orders"at160 msTime: 0 ms 80 ms 160 ms 240 ms |-------------|---------------------|---------------------| Input p2: [--- 80ms ---> X Error("502") Input p3: [------------- 160ms -------------> OK "Orders" Input p1: [------------------------ 240ms ------------------------> OK "Profile" Combinator outcomes on [p1, p2, p3]: - Promise.all([p1, p2, p3]) -> REJECTS at 80 ms with Error("502") - Promise.any([p1, p2, p3]) -> FULFILLS at 160 ms with "Orders" (ignores p2's failure at 80 ms) - Promise.allSettled([p1, p2, p3]) -> FULFILLS at 240 ms with: [ { status: "fulfilled", value: "Profile" }, // index 0 -> p1 (even though p1 finished last!) { status: "rejected", reason: Error("502") }, // index 1 -> p2 { status: "fulfilled", value: "Orders" } // index 2 -> p3 ]Empty iterables: vacuous truth versus zero candidates
Passing an empty array
[]exposes the exact logical symmetry between array predicates and promise combinators:Promise.all([])matches[].every(...) === true(vacuous truth): All zero required tasks have already succeeded, soPromise.all([])returns a promise already settled as fulfilled with[].Promise.allSettled([]): Zero tasks remain pending, so it returns a promise already settled as fulfilled with[].Promise.any([])matches[].some(...) === false: You asked for at least one winner from zero candidates, which is impossible.Promise.any([])returns a promise already settled as rejected withAggregateError("All promises were rejected")anderr.errors = [].- Contrast with
Promise.race([]): Because no input ever settles,Promise.race([])stayspendingforever.
Expression State right after call returns Value / Rejection Reason ------------------------- ------------------------------- ------------------------------------------ Promise.all([]) <fulfilled> [] Promise.allSettled([]) <fulfilled> [] Promise.any([]) <rejected> AggregateError (err.errors = []) Promise.race([]) <pending> (forever!) (never settles) Promise.all([1, 2]) <pending> (settles next tick) [1, 2] (non-empty always settles async)One subtle runtime distinction worth noting: for
[],all([]),allSettled([]), andany([])all mark their returned promise object settled before the function call returns (andPromise.any([])returns that rejected promise rather than throwing synchronously), while your.then/.catchhandlers still execute asynchronously on the next microtask. In contrast, for any non-empty iterable—even plain values likePromise.all([1, 2])—the returned promise starts<pending>and settles asynchronously on a microtask. In production code, always guard dynamic replica lists (or handleAggregateError) when callingPromise.any(urls.map(...)), because an emptyurlsarray immediately triggers the rejection path.Short-circuiting versus true network cancellation
Short-circuiting means the combined promise settles early without waiting for remaining inputs—when
Promise.allsees its first rejection, or whenPromise.anysees its first fulfillment.Crucially, short-circuiting does NOT cancel pending promises or abort underlying network I/O. A JavaScript
Promiseis a passive observation receipt for a result, not a control handle over the work producing it. WhenPromise.allrejects at80 ms: - The other in-flightfetchcalls keep their TCP sockets open, finish downloading payloads, and consume client memory and server CPU. - Any downstream side effects (such as database mutations triggered on remote services) still execute to completion. - Once those responses arrive, JavaScript simply discards their outcomes because the outerPromise.allhas already settled.To cancel in-flight HTTP calls for real, wire an
AbortController(a standard Web and Node.js API whosecontroller.signaltellsfetchto close the socket and reject withAbortErroras soon ascontroller.abort()is called) into every request:async function fetchJson(url, signal) { const res = await fetch(url, { signal }); if (!res.ok) { throw new Error(`HTTP ${res.status} from ${url}`); } // Parse the body BEFORE returning so Promise.any only resolves after body download completes! return await res.json(); } async function allWithCancel(taskFactories) { const controller = new AbortController(); try { return await Promise.all(taskFactories.map((run) => run(controller.signal))); } catch (err) { controller.abort(err); // first failure cancels all still-running sibling requests throw err; } } async function anyWithCancel(taskFactories) { const controller = new AbortController(); try { return await Promise.any(taskFactories.map((run) => run(controller.signal))); } finally { controller.abort(); // once one task finishes (including res.json()), abort slower replicas } }Notice two subtle engineering details above: each task is passed as a factory
(signal) => Promiseso requests cannot start without the signal attached, andfetchJsonawaitsres.json()inside the task sofinally { controller.abort(); }inanyWithCancelnever aborts the winner's body stream mid-download.Error retention and preventing unhandled rejections
Each combinator retains failure details differently: -
Promise.allretains only the first error: If servicep2rejects at80 msand servicep1rejects at200 ms,Promise.allrejects withp2's error and silently absorbsp1's error. If you need every error for audit logging, usePromise.allSettled. -Promise.anydiscards errors unless everything fails: Early errors are ignored if any replica succeeds; if all replicas fail,AggregateError.errorspreserves all reasons by input index. -Promise.allSettledretains every error as data: No exception is thrown; callers inspectitem.status === "rejected"and readitem.reason.How do UnhandledPromiseRejection crashes happen in practice? Because combinators attach handlers to every input right away, passing promises straight into
Promise.all/any/allSettledis safe. The classic crash comes from starting promises eagerly and awaiting them sequentially:0 ms: const p1 = fetchProfile(); // takes 400 ms to fulfill const p2 = fetchOrders(); // rejects at 50 ms! await p1; // execution pauses here watching ONLY p1... 50 ms: p2 rejects with ZERO handlers attached -> Node.js throws UnhandledPromiseRejection! 400 ms: await p2; // never reached (or reached too late)// DANGEROUS: p2 has no rejection handler while we wait 400 ms on p1! const p1 = fetchProfile(); const p2 = fetchOrders(); const profile = await p1; const orders = await p2; // SAFE: Promise.all attaches handlers to BOTH p1 and p2 immediately at 0 ms const [profile, orders] = await Promise.all([fetchProfile(), fetchOrders()]);Since Node.js 15, an unhandled rejection terminates the process by default (
--unhandled-rejections=throw), even ifawait p2sat inside atry / catchblock! Always hand concurrent promises directly to a combinator as soon as you create them, and alwaysawaitor.catch(...)the combinator's returned promise itself.Select the right combinator for each gateway scenario
- Analytics Overview Screen (4 independent report cards) ->
Promise.allSettled: Partial availability is required: one broken report card (say support queue) must never blank out the other three (revenue chart, active sessions, deployment log).Promise.allSettledwaits for all four and preserves input order[0..3]sooutcomes[i]maps directly tocards[i]. Always attach a per-card timeout (AbortSignal.timeout) so one hung endpoint cannot stall the entire overview screen:
js const outcomes = await Promise.allSettled( cards.map((c) => fetchJson(c.url, AbortSignal.timeout(2500))) ); outcomes.forEach((outcome, i) => { if (outcome.status === "fulfilled") { renderCard(cards[i], outcome.value); } else { renderCardFallback(cards[i], outcome.reason); } });- Pre-Commit Order Authorization (risk, stock, credit limit) ->
Promise.all(+AbortController): Every authorization check is mandatory, and checkout must fail fast the instant any check denies or crashes. Two rules are critical here: first, convert business denials and HTTP 4xx/5xx responses into rejections (fetchfulfills on HTTP500, and200 OK {"authorized": false}is a fulfilled promise unless you explicitlythrow!), and second, keep these parallel checks side-effect-free (commit stock holds or capture payment only after all three authorizations succeed):
``js async function verifyCheck(url, payload, signal) { const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), signal, }); if (!res.ok) throw new Error(${url} failed with HTTP ${res.status}); const body = await res.json(); if (!body.authorized) throw new Error(${url} denied: ${body.reason}`); return body; }await allWithCancel( [riskUrl, stockUrl, creditUrl].map( (url) => (signal) => verifyCheck(url, checkoutPayload, signal) ) ); ```
- Multi-Edge Key Bundle Fetch (manifest from 4 regional edge replicas) ->
Promise.any(+AbortController): Any valid copy of the immutable public-key manifest works, and we want minimum tail latency even if the closest replica returns an error. (Promise.racewould fail here because a fast502or DNS failure at15 mswould reject the whole call even when the other three replicas succeed at40 ms!) UsingfetchJson(which throws on!res.ok) insideanyWithCanceldelivers the fastest200 OKJSON bundle, aborts the three slower replica downloads, and surfaces all four replica errors inAggregateError.errorsif every region is down:
js const keyBundle = await anyWithCancel( replicaUrls.map((url) => (signal) => fetchJson(url, signal)) );- Analytics Overview Screen (4 independent report cards) ->
Intuition & how it works
Think of Promise.all, Promise.any, and Promise.allSettled as three rules a dispatcher can use after sending couriers out concurrently: Promise.all is an all-must-pass security gate (everyone must succeed, and the first failure stops the check immediately), Promise.any is a replica race for first success (the first courier who comes back with a valid package wins, and you only fail if every single courier comes back empty-handed), and Promise.allSettled is an end-of-shift roll call (wait until every courier returns and record each one's individual outcome in roll-call order).
Handling concurrent requests naively breaks reliability in three predictable ways. First, starting promises up front and awaiting them one by one (await p1; await p2;) wastes time sequentially and crashes Node.js with an unhandled promise rejection if p2 fails while execution is still paused on p1. Second, short-circuiting (settling the outer combined promise early) only stops JavaScript from waiting—it never closes open TCP sockets or stops remote servers unless you explicitly wire an AbortController (a cooperative cancellation signal) into each request. Third, fetch fulfills on HTTP 404/500 responses, so unless you throw on !res.ok, an error page looks like a "success" to both Promise.all and Promise.any.
Trace three concurrent inputs—p1 fulfills "Profile" at 240 ms, p2 rejects Error("502") at 80 ms, and p3 fulfills "Orders" at 160 ms:
1. Promise.all([p1, p2, p3]): Rejects at 80 ms with Error("502") as soon as p2 fails (p1 and p3 keep running in the background unless aborted).
2. Promise.any([p1, p2, p3]): Ignores p2's failure at 80 ms and fulfills at 160 ms with "Orders" as soon as p3 succeeds.
3. Promise.allSettled([p1, p2, p3]): Waits until 240 ms and fulfills with [{status: "fulfilled", value: "Profile"}, {status: "rejected", reason: Error("502")}, {status: "fulfilled", value: "Orders"}]—preserving [p1, p2, p3] input positions even though p1 finished last.
Key points
- Settlement semantics:
Promise.allfulfills when all fulfill and rejects on the first rejection;Promise.anyfulfills on the first fulfillment and rejects only when all reject (wrapping every reason inside anAggregateError, anErrorsubclass with an.errorsarray);Promise.allSettledfulfills once all settle and never rejects from input failures. - Result shapes and ordering:
allresolves to[v0, v1, ...]andallSettledresolves to[{status, value} | {status, reason}, ...], both strictly indexed in input order regardless of completion speed;anyresolves to the single value of whichever input fulfilled first (whileAggregateError.errorson total failure preserves input order). - Empty iterables (
[]):Promise.all([])andPromise.allSettled([])return promises already fulfilled with[](matching[].every(...) === true),Promise.any([])returns a promise already rejected withAggregateErroranderrors = [](matching[].some(...) === false), andPromise.race([])stayspendingforever. Any.then/.catchhandler still runs asynchronously on the microtask queue (callbacks executed right after the current synchronous turn). - Short-circuiting vs. cancellation: Promises are passive result handles without built-in cancellation; stopping in-flight HTTP calls requires passing
AbortController.signalto eachfetchand callingcontroller.abort()on early rejection (all) or completion (any). - Unhandled rejection prevention: Combinators attach internal rejection handlers to every input immediately at
0 ms, absorbing late rejections after short-circuiting; always pass concurrent promises directly into a combinator instead of awaiting pre-started promises one by one. - Scenario mapping: Independent analytics report cards ->
Promise.allSettled(with per-card timeouts); mandatory risk/stock/credit authorization ->Promise.all(throwing on!res.okand!body.authorized, plusAbortController); fastest healthy regional edge replica ->Promise.any(throwing on!res.ok, plusAbortControllerafter body parsing).
Common mistakes
- Forgetting that
fetchonly rejects on network failures, not HTTP4xx/5xx: Withoutif (!res.ok) throw ...(and throwing whenbody.authorized === false),Promise.anyhappily picks a fast502error page as the "winner," andPromise.allapproves denied checkouts. - Using
Promise.raceinstead ofPromise.anyfor multi-replica failover:Promise.racesettles on the first settled promise—fulfilled or rejected—so one fast DNS or502failure from a nearby broken replica aborts the whole call even when three healthy replicas are20 msbehind. - Assuming
Promise.allorPromise.anycancels losing HTTP requests: WithoutAbortController, losing requests keep sockets open, parse responses, and finish server-side mutations in the background. - Aborting a shared
AbortControllerinPromise.anybefore readingres.json(): IfPromise.anyresolves on rawfetchheaders andfinallycallscontroller.abort(), readingwinner.json()afterward fails because its body stream was just aborted! Alwaysawait res.json()inside each candidate task before returning. - Assuming
Promise.any([])fulfills withundefinedor hangs likePromise.race([]): An empty replica list immediately rejects withAggregateError. - Reading
result.valueonPromise.allSettledentries without checkingresult.status === "fulfilled": Rejected entries havevalue === undefinedand store their error underresult.reason. - Starting promises eagerly (
const a = f(); const b = g();) and runningawait a; await b;: Ifbrejects beforeafinishes, Node.js (--unhandled-rejections=throw) terminates the process beforeawait bis ever reached.
Follow-up questions
- How do you wire AbortController into concurrent fetch calls so losing or sibling HTTP requests actually abort when Promise.all fails fast or Promise.any finds a winner? Create one
AbortControllerper orchestration call, passcontroller.signalinto everyfetch(making sure each task awaitsres.json()before resolving), and callcontroller.abort()insidecatchforPromise.allor insidefinallyforPromise.any. Pendingfetchcalls immediately close their sockets and reject withAbortError, which the combinator's internal handlers silently absorb. To enforce an overall request deadline at the same time, compose signals withAbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]):
js
async function allWithDeadline(urls, timeoutMs) {
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(timeoutMs)]);
try {
return await Promise.all(urls.map((url) => fetchJson(url, signal)));
} catch (err) {
controller.abort(err); // cancel all still-running sibling requests
throw err;
}
}
-
Why can a single multi-hour straggler inside a large Promise.allSettled batch cause severe memory retention on a busy server, and how do you mitigate it?
Promise.allSettledholds its internal results array—plus closure references to the suspendedasynccaller's stack frame (incoming HTTP request objects, auth context, buffers)—until the very last input promise settles. If a gateway receives10requests/second, each fanning out to100upstream calls returning20 KBpayloads (~2 MBretained per aggregate), a single straggler endpoint hanging for1hour pins10 * 3,600 = 36,000pending aggregates in RAM—retaining roughly72 GBof memory and crashing the server with an out-of-memory error! Prevent this by attaching an explicit per-callAbortSignal.timeout(ms)to every input, processing and releasing large payloads inside individual.then(...)handlers when collecting everything at once is unnecessary, and bounding fan-out concurrency. -
In what ways does Promise.race behave differently from Promise.any when an early error occurs or when the input iterable is empty?
Promise.racesettles with whichever input settles first in either direction—if the fastest promise rejects at10 ms,Promise.raceimmediately rejects with that error even if every other input would fulfill at30 ms.Promise.anyinstead waits for the first fulfillment, ignoring early rejections unless every input rejects (in which case it rejects with anAggregateErrorcontaining all reasons). They also are opposites on[]:Promise.race([])stayspendingforever, whereasPromise.any([])immediately returns a rejected promise. UsePromise.racewhen racing work against an error timer (Promise.race([doWork(), rejectAfter(1000)])), and usePromise.anywhen querying redundant replicas where any healthy response suffices.
Follow-up questions
- How do you wire AbortController into concurrent fetch calls so losing or sibling HTTP requests actually abort when Promise.all fails fast or Promise.any finds a winner?
- Why can a single multi-hour straggler inside a large Promise.allSettled batch cause severe memory retention on a busy server, and how do you mitigate it?
- In what ways does Promise.race behave differently from Promise.any when an early error occurs or when the input iterable is empty?
Similar questions
- Merge Overlapping Intervals
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
More Micro1 interview questions
- Merge Overlapping Intervals Medium