Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.7 — Promise.all, allSettled, race and any
JavaScript · Example 3 of 4 ES2021+

Promise.race for a timeout, Promise.any for the first success

race took the first to settle, a rejection. any skipped mirror 1's failure and took the first success. When every promise failed, any rejected with an AggregateError listing them all.

Four static methods combine many promises into one: all waits for every one (and fails fast), allSettled waits for every outcome, race takes the first to settle, and any takes the first success.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Using wait(ms, value), load "A" (100 ms), "B" (200 ms) and "C" (50 ms) in parallel and log [ 'A', 'B', 'C' ].

02

Write firstAnswer(promises) that fulfils with the first success, or with the string "no answer" if every promise fails.

Explain it without notes

01

Compare Promise.all, allSettled, race and any: what does each fulfil and reject with?

02

If Promise.all makes nothing run in parallel, why does using it make code faster?

03

How would you add a timeout to a promise, and what is the limitation of doing it with race?

04

What is an AggregateError, and when do you see one?

Promise.race for a timeout, Promise.any for the first success ES2021+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

race: Timed out after 100 ms
any: file from mirror 2
AggregateError: All promises were rejected [ 'a failed', 'b failed' ]