Promise.race

First settles wins

Promise dot race takes several promises and mirrors the first one that settles. Settle means fulfill or reject, whichever happens first. The losers keep running, but their results are ignored. The already fulfilled promise settles before the timer, so the program always prints fast.

async function main(): Promise<void> { const fast: Promise<string> = Promise.resolve("fast"); const slow: Promise<string> = new Promise((resolve) => { setTimeout(() => resolve("slow"), 500); }); const win: string = await Promise.race([fast, slow]); console.log(win); } main();

fast

Race a timeout

A classic use races real work against a timer that rejects. If the timer wins, the await throws a timeout error. This keeps a slow backend from freezing the program. The program races one call that is already done and one that never settles, so both the answer and the timeout are printed.

function withTimeout(work: Promise<string>, ms: number): Promise<string> { const timer: Promise<string> = new Promise((_, reject) => { setTimeout(() => reject(new Error("timeout")), ms); }); return Promise.race([work, timer]); } async function run(): Promise<void> { console.log(await withTimeout(Promise.resolve("done"), 500)); try { await withTimeout(new Promise<string>(() => {}), 20); } catch (err: unknown) { console.log((err as Error).message); } } run();

done
timeout

Any success (Promise.any)

Promise dot any waits for the first fulfillment and skips rejections until one success lands. It only rejects when every input rejects. Use it to try mirrors and take the first healthy answer. The program rejects one mirror and fulfils the other, so the healthy answer is printed.

async function main(): Promise<void> { const best: string = await Promise.any([ Promise.reject(new Error("one down")), Promise.resolve("mirror two"), ]); console.log(best); } main();

mirror two

When racing helps

Racing fits timeouts, first mirror wins, and user cancel flows. It does not speed up work that must all finish. For full results keep all, for fastest answer keep race. Both promises here are already fulfilled, so the first one in the list wins and the program prints a.

async function firstMirror(a: Promise<string>, b: Promise<string>): Promise<string> { return Promise.race([a, b]); } async function main(): Promise<void> { const v = await firstMirror(Promise.resolve("a"), Promise.resolve("b")); console.log(v); } main();

a

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Promise.race settle with?

    Answer

    The outcome of the first input that settles

    Race mirrors whichever input fulfils or rejects first, so a rejection can win the race too.

  2. What happens to the promises that lose a race?

    Answer

    They keep running and their results are ignored

    Race only picks a winner; stopping the rest takes an abort signal or another cancel step.

  3. How is Promise.any different from Promise.race?

    Answer

    It skips rejections and waits for the first fulfillment

    Any ignores a rejected input and keeps waiting, while race would take that rejection as the result.

  4. When does Promise.any reject?

    Answer

    Only when every input rejects

    Any needs one success, so it gives up and rejects with an AggregateError only after every input has rejected.

  5. What does this program print? async function main(): Promise<void> { const fast: Promise<string> = Promise.resolve("fast"); const slow: Promise<string> = new Promise((resolve) => { setTimeout(() => resolve("slow"), 500); }); const win: string = await Promise.race([fast, slow]); console.log(win); } main();

    Answer

    fast

    The fulfilled promise is already settled when the race starts, so it wins long before the timer.

  6. What does this program print? function withTimeout(work: Promise<string>, ms: number): Promise<string> { const timer: Promise<string> = new Promise((_, reject) => { setTimeout(() => reject(new Error("timeout")), ms); }); return Promise.race([work, timer]); } async function run(): Promise<void> { console.log(await withTimeout(Promise.resolve("done"), 500)); try { await withTimeout(new Promise<string>(() => {}), 20); } catch (err: unknown) { console.log((err as Error).message); } } run();

    Answer

    done / timeout

    The first call wins with the finished work, and the second has no work to win with, so the timer rejects and its message is printed.

  7. What does this program print? async function main(): Promise<void> { const best: string = await Promise.any([ Promise.reject(new Error("one down")), Promise.resolve("mirror two"), ]); console.log(best); } main();

    Answer

    mirror two

    Any skips the rejected input and fulfils with the first healthy answer.

  8. What does this program print? async function firstMirror(a: Promise<string>, b: Promise<string>): Promise<string> { return Promise.race([a, b]); } async function main(): Promise<void> { const v = await firstMirror(Promise.resolve("a"), Promise.resolve("b")); console.log(v); } main();

    Answer

    a

    Both promises are already fulfilled, and race takes the first one of the list.

  9. A program must have every request finished before it moves on. Why is Promise.race the wrong tool there?

    Answer

    It returns as soon as the first settles and the others keep running

    Race is about the first answer; a program that needs all of them waits with Promise.all instead.

  10. What does the compiler say about this program? const win: string = Promise.race([Promise.resolve("fast")]); console.log(win);

    Answer

    error TS2322: Type 'Promise<string>' is not assignable to type 'string'.

    Race returns a promise, so the value has to be awaited before it can be stored in a string.

Article author: Arthur Isaev