Promise.all, allSettled & race: The Relay Team

Promise.all, allSettled & race: The Relay Team in TypeScript: A catering bakery has four ovens set along one wall, and a large event order needs four different…

The Analogy: A Bank of Ovens in a Catering Bakery

A catering bakery has four ovens set along one wall, and a large event order needs four different items baked: a sponge, a tart, a loaf, and a batch of buns. The baker could run them one after another in a single oven, but the ovens are independent, so instead all four are loaded at once and run together. The whole order is then ready in the time of the slowest item rather than the sum of all four, which is the entire reason for using more than one oven. This is fanning out independent work: the tasks do not depend on each other, so there is nothing to be gained by making them wait in line.

What counts as "the order is ready" depends on the job, and this is where the four rules diverge. For a boxed set that ships as one delivery, every item must come out baked or the order cannot go at all, and if a single item burns the whole boxed order is scrapped. That is the all-or-nothing rule: wait for every oven to finish, and treat one failure as failure of the batch. It is the right rule when the customer needs the complete set and a partial set is worthless, but it is the wrong rule the moment a partial delivery would still have been useful.

The other rules trade that strictness for tolerance. If the baker only wants a status sheet at the end, noting which items baked and which burnt without the batch ever being declared a failure, that is the settle-everything rule: wait for all four ovens and record the outcome of each. If a walk-in customer needs the very first item out of any oven, taking it whether it came out perfect or slightly catching, that is the first-to-finish rule: the first oven to ping decides the outcome, good or bad. And if the baker wants the first properly baked item and is willing to ignore any that burn unless every last oven burns its item, that is the first-success rule.

The failure mode is choosing the strict rule out of habit when a tolerant one was called for, and misunderstanding what "done" actually does. Scrapping four items because one burnt is pure waste when a status sheet would have let the baker rebake only the burnt one. The subtler trap is assuming that deciding you have the item you want also switches the other ovens off. It does not: the moment the baker grabs the first tray for the walk-in customer, the other three ovens keep heating and baking to completion regardless, because the decision to stop waiting is not the decision to stop the work. A baker who forgets this comes back to three more finished trays and a gas bill for ovens nobody was watching. Stopping the work needs someone to walk over and physically switch the ovens off, which in code is an explicit cancellation signal, not the mere fact that you stopped awaiting the result.


Syntax or Core Structure

The four combinators all take a list of promises and differ only in when they consider the group finished. The workhorse is Promise.all, which waits for every promise to fulfil and hands the results back as a tuple in input order.

// src/all.ts
async function bake(tray: string, minutes: number): Promise<string> {
    return tray + ":" + minutes;
}

async function main(): Promise<void> {
    const [sponge, tart, loaf] = await Promise.all([
        bake("sponge", 30),
        bake("tart", 20),
        bake("loaf", 45),
    ]);
    console.log(sponge);
    console.log(tart);
    console.log(loaf);
    console.log("done " + [sponge, tart, loaf].length);
}

main();

Output:

sponge:30
tart:20
loaf:45
done 3

The result array comes back in input order, not finish order. Even though the tart takes the fewest minutes, sponge is still the first element, because Promise.all fills each slot positionally from the input list. The typing is the part people miss: Promise.all on an array literal returns Promise<[string, string, string]>, a tuple, not Promise<string[]>. If the three calls had returned a User, a list of posts, and a settings object, destructuring would still give each binding its exact type rather than a widened union, because TypeScript has dedicated overloads for tuples.

// A promise starts running when it is created, not when it is awaited.
const first = bake("sponge", 30);   // already running
const second = bake("tart", 20);    // already running
const a = await first;              // both were in flight before this line
const b = await second;

This is why kicking two promises off and then awaiting them is still concurrent: the work began at creation, so by the time the first await runs, both are already in flight. Sequential await is only necessary when a later step genuinely needs an earlier step's value.


Technical Depth: Settle Everything, Then Extract

Promise.all rejects the instant one input rejects, and every other result is lost with it. When a partial result is still worth having, that is the wrong rule; Promise.allSettled is the status-sheet rule. It never rejects, and it resolves with a discriminated union describing the fate of each input.

allSettled and its discriminated union

// src/settled.ts
async function bake(tray: string): Promise<string> {
    if (tray === "tart") {
        throw new Error("burnt: " + tray);
    }
    return "baked:" + tray;
}

async function main(): Promise<void> {
    const trays = ["sponge", "tart", "loaf"];
    const results = await Promise.allSettled(trays.map(bake));
    for (const r of results) {
        if (r.status === "fulfilled") {
            console.log("ok " + r.value);
        } else {
            console.log("no " + (r.reason as Error).message);
        }
    }
}

main();

Output:

ok baked:sponge
no burnt: tart
ok baked:loaf

The status field is the discriminant, so this is the same narrowing you saw with a Result union: r.value exists only in the "fulfilled" branch and r.reason only in the "rejected" branch. One sharp edge is that reason is typed any, because the standard library has no way to know what was thrown, so a real handler should push it through a toError helper rather than trusting the as Error cast shown here for brevity.

Extracting the successes with a type predicate

// src/fulfilled.ts
async function bake(tray: string): Promise<string> {
    if (tray === "tart") {
        throw new Error("burnt");
    }
    return tray;
}

function fulfilled<T>(results: PromiseSettledResult<T>[]): T[] {
    return results
        .filter((r): r is PromiseFulfilledResult<T> => r.status === "fulfilled")
        .map((r) => r.value);
}

async function main(): Promise<void> {
    const trays = ["sponge", "tart", "loaf", "buns"];
    const settled = await Promise.allSettled(trays.map(bake));
    const good = fulfilled(settled);
    console.log("good: " + good.length);
    console.log(good.join(","));
}

main();

Output:

good: 3
sponge,loaf,buns

Four trays go in, the tart burns, and fulfilled returns the three survivors in input order. The predicate (r): r is PromiseFulfilledResult<T> is what makes .map((r) => r.value) compile: an ordinary filter would still be typed as the full settled union, on which .value does not exist for every member, so the type predicate is what narrows the array element to the fulfilled shape.

race and any

Promise.race settles as soon as the first input settles, success or failure alike, while Promise.any waits for the first fulfilment and ignores rejections unless every input rejects. The deterministic case for any is when exactly one source can succeed.

// src/any.ts
async function fromCache(): Promise<string> {
    throw new Error("cache miss");
}
async function fromApi(): Promise<string> {
    throw new Error("api down");
}
async function fromDb(): Promise<string> {
    return "db-value";
}

async function main(): Promise<void> {
    const value = await Promise.any([fromCache(), fromApi(), fromDb()]);
    console.log(value);
}

main();

Output:

db-value

Two of the three sources reject and only fromDb fulfils, so Promise.any resolves to "db-value" no matter which order they settle in; the rejections are simply ignored. Had all three rejected, any would reject with an AggregateError whose .errors array holds every failure. race differs precisely here: it would have taken whichever settled first even if that was one of the rejections. A useful typing detail for deadlines is Promise<never>: a timeout leg that only ever rejects contributes never to the union, and since never disappears from a union, the race keeps the exact success type.

// A timeout leg types cleanly because Promise<never> vanishes from the union.
declare function afterDeadline(ms: number): Promise<never>;
async function fresh(): Promise<string> {
    return Promise.race([fromDb(), afterDeadline(2000)]);   // Promise<string>
}

Choosing a Combinator

The four combinators are one decision: how much tolerance for partial failure does this particular job need. The table lines up the rules side by side.

MethodResolves whenRejects whenResult shape
allevery input fulfilsthe first rejectiona tuple in input order
allSettledevery input settlesneverone settled entry per input
racethe first input settlesthe first settle is a rejectionthe settled value
anythe first fulfilmentevery input rejectsthe first success

The one caveat that catches everyone out is that none of these cancels anything. When race picks a winner or all bails on a rejection, the other promises keep running to completion and their results are merely discarded, exactly like the ovens that stay hot after the baker has taken the tray they wanted. Real cancellation needs an AbortSignal handed to the underlying work.

// Deciding you are done waiting is not the same as stopping the work.
const controller = new AbortController();
const inflight = fetch("/api/slow", { signal: controller.signal });
controller.abort();   // this actually stops the request

// AbortSignal.timeout covers the common deadline case for you.
const guarded = fetch("/api/slow", { signal: AbortSignal.timeout(3000) });

Bounded concurrency

Firing thousands of promises at once with Promise.all will exhaust sockets or trip a rate limit. A mapLimit helper caps how many run at a time by starting a fixed pool of workers that pull from a shared index, writing each result to its own slot so order is preserved.

// src/maplimit.ts
async function mapLimit<T, R>(
    items: readonly T[],
    limit: number,
    fn: (item: T, index: number) => Promise<R>
): Promise<R[]> {
    const out: R[] = new Array(items.length);
    let next = 0;
    const count = Math.min(limit, items.length);
    const workers = Array.from({ length: count }, async () => {
        while (next < items.length) {
            const i = next++;
            out[i] = await fn(items[i], i);
        }
    });
    await Promise.all(workers);
    return out;
}

async function main(): Promise<void> {
    const nums = [1, 2, 3, 4, 5];
    const doubled = await mapLimit(nums, 2, async (n) => n * 2);
    console.log(doubled.join(","));
    console.log("sum " + doubled.reduce((a, b) => a + b, 0));
}

main();

Output:

2,4,6,8,10
sum 30

The generics carry the types across without any annotation at the call site: T is inferred from items, R from the value fn resolves to, so doubled is number[]. Only two workers run at once, yet out is written by index rather than pushed, so the results stay in input order regardless of which worker finished a given slot first: [2, 4, 6, 8, 10], summing to 30.


Real World Example: A Morning Production Board That Degrades Gracefully

The bakery wants a single board every morning showing the tray count from each of its four ovens, pulled from four independent oven controllers. The controllers fail independently: one may be offline for maintenance while the others report fine. The board should still render with whatever data it can get rather than showing nothing because one controller was down, so each oven's promise carries its own .catch fallback and the fan-out uses Promise.all over the four already-guarded promises.

// src/board.ts
interface Section {
    name: string;
    trays: number;
}

async function ovenA(): Promise<Section> {
    return { name: "ovenA", trays: 12 };
}
async function ovenB(): Promise<Section> {
    throw new Error("ovenB controller offline");
}
async function ovenC(): Promise<Section> {
    return { name: "ovenC", trays: 8 };
}
async function ovenD(): Promise<Section> {
    return { name: "ovenD", trays: 15 };
}

function empty(name: string): Section {
    return { name: name, trays: 0 };
}

function pad(text: string, width: number): string {
    const gap = width - text.length;
    return text + " ".repeat(gap > 0 ? gap : 0);
}

async function main(): Promise<void> {
    const sections: Section[] = await Promise.all([
        ovenA().catch(() => empty("ovenA")),
        ovenB().catch(() => empty("ovenB")),
        ovenC().catch(() => empty("ovenC")),
        ovenD().catch(() => empty("ovenD")),
    ]);

    let total = 0;
    console.log("ovens: " + sections.length);
    console.log(pad("OVEN", 8) + "TRAYS");
    for (const s of sections) {
        total += s.trays;
        console.log(pad(s.name, 8) + s.trays);
    }
    console.log("total: " + total);
}

main();

Output:

ovens: 4
OVEN    TRAYS
ovenA   12
ovenB   0
ovenC   8
ovenD   15
total: 35

Trace the four ovens. ovenA, ovenC, and ovenD resolve with 12, 8, and 15 trays. ovenB throws, but its rejection is caught by its own .catch, which substitutes empty("ovenB") before Promise.all ever sees a rejection, so the board renders all four rows and the total comes to 12 + 0 + 8 + 15 = 35. The results stay in input order because Promise.all fills positionally, so ovenA is always the first row regardless of which controller answered first.

The pattern worth taking away is the per-promise .catch inside Promise.all. A bare Promise.all would reject the whole board the moment ovenB threw, discarding the three good readings; guarding each promise individually turns "all or nothing" into "all, with graceful holes." The fallback value also fixes the type, so sections is a clean Section[] with no rejection to narrow, and the report loop never touches a try.

That same graceful degradation is the design's real flaw, and it is worth stating plainly. A failed oven is folded into empty(name) with trays: 0, which is byte-for-byte indistinguishable from an oven that genuinely baked nothing this morning, so a controller outage silently masquerades as an idle oven and the total quietly understates true production with no alert raised anywhere; a real board would carry a status flag per section and surface the difference between "zero" and "unknown." A second limitation is that there is no deadline on any oven: because Promise.all waits for the slowest input, a single hung controller would stall the entire board indefinitely, which is exactly the case a Promise.race against a timeout leg, backed by a real AbortSignal, exists to handle.


Common Mistakes

  1. Sequential await in a loop for independent work. Awaiting each call before starting the next runs them one at a time; use Promise.all(items.map(fn)) when the calls do not depend on one another.
  2. Using Promise.all when partial success is acceptable. A single rejection discards every other result, so reach for Promise.allSettled whenever the successes are still worth keeping.
  3. Ignoring that allSettled's reason is typed any. The standard library cannot know what was thrown, so normalise the reason through a toError helper before you read a .message off it.
  4. Filtering without a type predicate, then reading .value. A plain .filter(r => r.status === "fulfilled") stays typed as the full union, so .map(r => r.value) will not compile, and papering over it with as hides the real fix.
  5. Assuming race or all cancels the losers. The other promises run to completion and their results are merely discarded; only an AbortSignal handed to the underlying work actually stops it.
  6. Confusing race with any. race settles on the first input to settle even if that is a rejection, whereas any waits for the first fulfilment and only rejects when every input fails.
  7. Running Promise.all over thousands of items. Firing them all at once exhausts sockets or trips rate limits, so bound the fan-out with a mapLimit helper.
  8. Awaiting inside .forEach. forEach ignores the returned promises, so the loop finishes instantly and every rejection is unhandled; use for...of for sequential work or map plus Promise.all for concurrent.
  9. Forgetting the await on Promise.all itself. Without it you destructure the pending promise rather than its results, so each binding is a Promise, not the resolved value you expected.

Best Practices

  • Default to Promise.all for independent work. Reach for a sequential for...of loop only when step N genuinely needs step N-1's value.
  • Destructure Promise.all from an array literal. Passing an array literal directly is what preserves the tuple types, so each binding keeps its exact type instead of widening to a union.
  • Use allSettled whenever partial results are useful. Pair it with a typed fulfilled() helper built on a type predicate to extract the successes cleanly.
  • Attach .catch(fallback) to non-critical promises inside all. Guarding each promise means one flaky input cannot sink the whole batch, and the fallback fixes the element type.
  • Implement deadlines with race and a Promise<never> leg, or AbortSignal.timeout. The never leg keeps the success type clean, and the signal is what actually cancels the work.
  • Cap concurrency with a mapLimit helper. Any list whose length you do not control should run through a bounded worker pool rather than a single unbounded Promise.all.
  • Await critical dependencies first, then fan out the rest. Do not make an entire page wait on a non-essential widget when the essential data could have rendered already.
  • Remember that nothing here cancels on its own. When a losing promise is expensive, pair the combinator with an AbortSignal so the discarded work actually stops rather than running on unwatched.

Practice Exercises

  1. The Speed-Up. Take three independent sequential await calls and convert them into a single destructured Promise.all, then confirm in the editor that each destructured binding keeps its own specific type rather than a widened union.
  2. The Report Card. Run five operations where two are guaranteed to reject, collect them with Promise.allSettled, print a summary counting successes and failures, and then extract just the successful values with a type-predicate filter.
  3. The Deadline. Write withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> using Promise.race against a Promise<never> leg, then rewrite it with AbortSignal.timeout and explain in a comment which version actually stops the underlying work.
  4. The Throttle. Implement mapLimit and prove with a shared counter that no more than limit operations ever run at once, and that the returned array is still in input order even when later items finish before earlier ones.