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:

  1. 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 [].
  2. Short-Circuiting, Cancellation, and Error Handling: Clarify what happens to still-running promises and open network sockets when Promise.all fails early or Promise.any finds 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.
  3. 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, AggregateError structure, 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 sequential await on pre-started promises triggers unhandled rejections.
  • Production-ready scenario mapping: Pair each gateway use case with the right combinator plus essential HTTP safeguards (!res.ok checks, body-read timing, timeouts, and cooperative cancellation).

Step-by-step walkthrough

  1. How JavaScript promise combinators work under the hood

    A JavaScript Promise is a placeholder for the result of an asynchronous operation: it starts pending and permanently settles once into either fulfilled (with a value) or rejected (with an error reason). A concurrency combinator takes an iterable of inputs—usually promises representing concurrent API calls—and returns one single combined Promise.

    Before comparing Promise.all, Promise.any, and Promise.allSettled, note three foundational rules they all share:

    1. Non-promise values are wrapped automatically: Each element is passed through Promise.resolve(element), so mixing plain values like 42 with fetch(...) calls works seamlessly.
    2. 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.
    3. 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).
  2. 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 AggregateError whose .errors array 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 v from the winning promise. Array of outcome objects: { status: "fulfilled", value } or { status: "rejected", reason }.
    Result Ordering Preserves input iterable order (results[i] matches inputs[i]). Returns whichever input fulfilled first in time (on total failure, err.errors[i] preserves input order). Preserves input iterable order (results[i] matches inputs[i]).
    Empty Iterable ([]) Returns an already-fulfilled promise with []. Returns an already-rejected promise with AggregateError (errors: []). Returns an already-fulfilled promise with [].

    Here AggregateError is a standard JavaScript Error subclass designed to bundle multiple failures into one error object via its .errors array property.

    Trace all three on the same three concurrent upstream calls: - p1: fulfills with "Profile" at 240 ms - p2: rejects with Error("502") at 80 ms - p3: fulfills with "Orders" at 160 ms

    Time:    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
        ]
    
  3. 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, so Promise.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 with AggregateError("All promises were rejected") and err.errors = [].
    • Contrast with Promise.race([]): Because no input ever settles, Promise.race([]) stays pending forever.
    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([]), and any([]) all mark their returned promise object settled before the function call returns (and Promise.any([]) returns that rejected promise rather than throwing synchronously), while your .then / .catch handlers still execute asynchronously on the next microtask. In contrast, for any non-empty iterable—even plain values like Promise.all([1, 2])—the returned promise starts <pending> and settles asynchronously on a microtask. In production code, always guard dynamic replica lists (or handle AggregateError) when calling Promise.any(urls.map(...)), because an empty urls array immediately triggers the rejection path.

  4. Short-circuiting versus true network cancellation

    Short-circuiting means the combined promise settles early without waiting for remaining inputs—when Promise.all sees its first rejection, or when Promise.any sees its first fulfillment.

    Crucially, short-circuiting does NOT cancel pending promises or abort underlying network I/O. A JavaScript Promise is a passive observation receipt for a result, not a control handle over the work producing it. When Promise.all rejects at 80 ms: - The other in-flight fetch calls 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 outer Promise.all has already settled.

    To cancel in-flight HTTP calls for real, wire an AbortController (a standard Web and Node.js API whose controller.signal tells fetch to close the socket and reject with AbortError as soon as controller.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) => Promise so requests cannot start without the signal attached, and fetchJson awaits res.json() inside the task so finally { controller.abort(); } in anyWithCancel never aborts the winner's body stream mid-download.

  5. Error retention and preventing unhandled rejections

    Each combinator retains failure details differently: - Promise.all retains only the first error: If service p2 rejects at 80 ms and service p1 rejects at 200 ms, Promise.all rejects with p2's error and silently absorbs p1's error. If you need every error for audit logging, use Promise.allSettled. - Promise.any discards errors unless everything fails: Early errors are ignored if any replica succeeds; if all replicas fail, AggregateError.errors preserves all reasons by input index. - Promise.allSettled retains every error as data: No exception is thrown; callers inspect item.status === "rejected" and read item.reason.

    How do UnhandledPromiseRejection crashes happen in practice? Because combinators attach handlers to every input right away, passing promises straight into Promise.all / any / allSettled is 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 if await p2 sat inside a try / catch block! Always hand concurrent promises directly to a combinator as soon as you create them, and always await or .catch(...) the combinator's returned promise itself.

  6. Select the right combinator for each gateway scenario

    1. 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.allSettled waits for all four and preserves input order [0..3] so outcomes[i] maps directly to cards[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); } });

    1. 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 (fetch fulfills on HTTP 500, and 200 OK {"authorized": false} is a fulfilled promise unless you explicitly throw!), 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) ) ); ```

    1. 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.race would fail here because a fast 502 or DNS failure at 15 ms would reject the whole call even when the other three replicas succeed at 40 ms!) Using fetchJson (which throws on !res.ok) inside anyWithCancel delivers the fastest 200 OK JSON bundle, aborts the three slower replica downloads, and surfaces all four replica errors in AggregateError.errors if every region is down:

    js const keyBundle = await anyWithCancel( replicaUrls.map((url) => (signal) => fetchJson(url, signal)) );

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.all fulfills when all fulfill and rejects on the first rejection; Promise.any fulfills on the first fulfillment and rejects only when all reject (wrapping every reason inside an AggregateError, an Error subclass with an .errors array); Promise.allSettled fulfills once all settle and never rejects from input failures.
  • Result shapes and ordering: all resolves to [v0, v1, ...] and allSettled resolves to [{status, value} | {status, reason}, ...], both strictly indexed in input order regardless of completion speed; any resolves to the single value of whichever input fulfilled first (while AggregateError.errors on total failure preserves input order).
  • Empty iterables ([]): Promise.all([]) and Promise.allSettled([]) return promises already fulfilled with [] (matching [].every(...) === true), Promise.any([]) returns a promise already rejected with AggregateError and errors = [] (matching [].some(...) === false), and Promise.race([]) stays pending forever. Any .then/.catch handler 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.signal to each fetch and calling controller.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.ok and !body.authorized, plus AbortController); fastest healthy regional edge replica -> Promise.any (throwing on !res.ok, plus AbortController after body parsing).

Common mistakes

  • Forgetting that fetch only rejects on network failures, not HTTP 4xx/5xx: Without if (!res.ok) throw ... (and throwing when body.authorized === false), Promise.any happily picks a fast 502 error page as the "winner," and Promise.all approves denied checkouts.
  • Using Promise.race instead of Promise.any for multi-replica failover: Promise.race settles on the first settled promise—fulfilled or rejected—so one fast DNS or 502 failure from a nearby broken replica aborts the whole call even when three healthy replicas are 20 ms behind.
  • Assuming Promise.all or Promise.any cancels losing HTTP requests: Without AbortController, losing requests keep sockets open, parse responses, and finish server-side mutations in the background.
  • Aborting a shared AbortController in Promise.any before reading res.json(): If Promise.any resolves on raw fetch headers and finally calls controller.abort(), reading winner.json() afterward fails because its body stream was just aborted! Always await res.json() inside each candidate task before returning.
  • Assuming Promise.any([]) fulfills with undefined or hangs like Promise.race([]): An empty replica list immediately rejects with AggregateError.
  • Reading result.value on Promise.allSettled entries without checking result.status === "fulfilled": Rejected entries have value === undefined and store their error under result.reason.
  • Starting promises eagerly (const a = f(); const b = g();) and running await a; await b;: If b rejects before a finishes, Node.js (--unhandled-rejections=throw) terminates the process before await b is 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 AbortController per orchestration call, pass controller.signal into every fetch (making sure each task awaits res.json() before resolving), and call controller.abort() inside catch for Promise.all or inside finally for Promise.any. Pending fetch calls immediately close their sockets and reject with AbortError, which the combinator's internal handlers silently absorb. To enforce an overall request deadline at the same time, compose signals with AbortSignal.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.allSettled holds its internal results array—plus closure references to the suspended async caller's stack frame (incoming HTTP request objects, auth context, buffers)—until the very last input promise settles. If a gateway receives 10 requests/second, each fanning out to 100 upstream calls returning 20 KB payloads (~2 MB retained per aggregate), a single straggler endpoint hanging for 1 hour pins 10 * 3,600 = 36,000 pending aggregates in RAM—retaining roughly 72 GB of memory and crashing the server with an out-of-memory error! Prevent this by attaching an explicit per-call AbortSignal.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.race settles with whichever input settles first in either direction—if the fastest promise rejects at 10 ms, Promise.race immediately rejects with that error even if every other input would fulfill at 30 ms. Promise.any instead waits for the first fulfillment, ignoring early rejections unless every input rejects (in which case it rejects with an AggregateError containing all reasons). They also are opposites on []: Promise.race([]) stays pending forever, whereas Promise.any([]) immediately returns a rejected promise. Use Promise.race when racing work against an error timer (Promise.race([doWork(), rejectAfter(1000)])), and use Promise.any when querying redundant replicas where any healthy response suffices.

Follow-up questions

Similar questions

More Micro1 interview questions

All 2 Micro1 questions →