Promise combinators
Relay delivers one event to ten targets. With Promise.all, one target returning 503 rejects the
whole thing: the report says “failed” and says nothing about the nine that worked. For the config
store, Relay has three mirrors and needs whichever answers first, but Promise.race returns the
first mirror to fail just as happily.
The four combinators differ in what they wait for and what they do with failures. Choosing one is
a decision about the case, not a style choice. Promises and async introduced all and
allSettled. This lesson puts all four side by side.
What each one does
Section titled “What each one does”| Combinator | Resolves when | Rejects when |
|---|---|---|
Promise.all |
all fulfil | the first one rejects |
Promise.allSettled |
all have settled | never |
Promise.race |
the first one settles (either way) | the first one settles as rejected |
Promise.any |
the first one fulfils | all reject |
All of them start nothing. The promises already run when you pass them in. The combinator only decides how to wait.
Typed results
Section titled “Typed results”all and allSettled keep a tuple, one type per position. race and any give a union of the
inputs’ types:
declare const job: Promise<{ readonly id: string }>declare const count: Promise<number>
async function main() { const [j, n] = await Promise.all([job, count]) // [{ id: string }, number] const settled = await Promise.allSettled([job, count]) // [PromiseSettledResult<{ id: string }>, PromiseSettledResult<number>] const first = await Promise.race([job, count]) // { id: string } | number const any = await Promise.any([job, count]) // { id: string } | number return [j, n, settled, first, any]}The tuple only survives if you pass an array literal or a tuple type. A Promise<number>[] gives
back number[], with the position information gone.
allSettled for a delivery report
Section titled “allSettled for a delivery report”The report must list every outcome. allSettled never rejects, and each result is a union
discriminated by status:
interface Target { readonly name: string send(body: string): Promise<number>}
async function deliver(targets: readonly Target[], body: string) { const results = await Promise.allSettled(targets.map((t) => t.send(body))) return results.map((r, i) => ({ target: targets[i]?.name, ok: r.status === "fulfilled", }))}reason on a rejected result is any. Treat it as unknown, as in unknown, and
narrow it before reading .message.
any and AggregateError
Section titled “any and AggregateError”Promise.any ignores failures until every input has failed. Then it rejects with an
AggregateError, whose errors array holds each reason in input order:
declare const mirrors: readonly { ping(): Promise<void> }[]
async function anyMirror(): Promise<void> { try { await Promise.any(mirrors.map((m) => m.ping())) } catch (error) { if (error instanceof AggregateError) { error.errors // any[]: one reason per mirror } }}An empty list also rejects with an AggregateError, with no errors in it. Decide whether “no
mirrors” is a different case from “all mirrors failed” before you rely on this.
race for deadlines, and the loser
Section titled “race for deadlines, and the loser”race settles with the first promise to settle. That fits a deadline: race the task against a timer
that resolves. It does not cancel the loser, which keeps running. For stopping the work itself, see
cancellation.
type Outcome<T> = { readonly ok: true; readonly value: T } | { readonly ok: false }
function orTimeout<T>(task: Promise<T>, timedOut: Promise<void>): Promise<Outcome<T>> { return Promise.race([ task.then((value): Outcome<T> => ({ ok: true, value })), timedOut.then((): Outcome<T> => ({ ok: false })), ])}Both branches map to the same Outcome<T>, so the race has one result type.
Unhandled rejections
Section titled “Unhandled rejections”A promise that rejects with nobody listening raises an unhandled rejection, and Bun and Node can
exit on it. Combinators attach handlers to everything you pass in, so inside all or any the
losers’ failures are handled (and dropped). The danger is outside them:
declare function send(body: string): Promise<void>
async function risky() { const a = send("a") // starts now const b = send("b") // starts now await a // if this takes long and b rejects meanwhile, b has no handler yet await b}If b rejects while a is still pending, the runtime reports it before the await b line runs.
Pass both to a combinator at once, as await Promise.all([a, b]), so each has a handler from the
start.
Exercise
Section titled “Exercise”Four functions, one per case. The starter uses the wrong combinator in each, so tests fail where the behaviour differs. The tests control timing with promises they resolve by hand, so nothing waits.
all: every result or the first failure.allSettled: every outcome, never rejects.race: the first to settle.any: the first success,AggregateErrorif none.- Tuples keep per-position types for
allandallSettled.raceandanygive a union. - Delivery reports use
allSettled, the first healthy mirror usesany, and deadlines userace. raceandanydo not cancel the losers.- Hand promises to a combinator together, so none is left without a handler.
Further reading
Section titled “Further reading”- Promise.any() (MDN): first fulfilment wins, and when you get an AggregateError.
- Promise.allSettled() (MDN): collect every outcome without short-circuiting.