← Back to Node.js, page 6

nodejs-0117 · Medium mid

Four promise combinators receive tasks that finish at different times, and some of them fail. ```js const wait = (ms, value, fail) => new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms)); const show = (p) => p.then((v) => 'ok ' + JSON.stringify(v), (e) => 'error ' + e.message); (async () => { console.log('all ->', await show(Promise.all([wait(30, 'a'), wait(10, 'b'), wait(20, 'c')]))); console.log('all fails ->', await show(Promise.all([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')]))); console.log('race ->', await show(Promise.race([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')]))); console.log('any ->', await show(Promise.any([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')]))); console.log('any fails ->', await show(Promise.any([wait(10, 'x', true), wait(20, 'y', true)]))); console.log('allSettled ->', (await Promise.allSettled([wait(10, 'a'), wait(20, 'b', true)])).map((r) => r.status).join(',')); })(); ``` What does it print, and why?

Promise.all keeps input order in its result and rejects on the first failure. Promise.race settles with whichever promise settles first, success or failure. Promise.any fulfils with the first success and ignores failures, and rejects with an AggregateError if all fail. Promise.allSettled never rejects and reports every outcome.

Full answer

Predict with a timeline of 10, 20 and 30 ms.

  • all: all three succeed. The result array follows the input order, not the finish order: ["a","b","c"].
  • all fails: b fails at 10 ms. The result is a rejection with error b right away. The other tasks keep running but their results are ignored. all does not cancel them.
  • race: b settles first (at 10 ms) with a failure, so race rejects with error b. race copies the first settlement, whether success or failure.
  • any: b fails at 10 ms and is ignored. c succeeds at 20 ms. any fulfils with "c". Task a finishes later and is ignored.
  • any fails: both fail, so any rejects with an AggregateError. Its message is 'All promises were rejected', and the individual errors are in .errors.
  • allSettled: never rejects. It resolves with objects { status, value } or { status, reason }. Statuses: fulfilled, rejected.

Which to use:

  • all: when every result is needed, and one failure means the whole job failed.
  • allSettled: when you want every outcome and you handle partial failure.
  • race: for timeouts (race against a timer) or the first response. Remember that losers are not cancelled, so pair it with an AbortController.
  • any: for redundancy, such as asking several mirrors and taking the first good answer.

One more trap: tasks start when they are created, not when you pass them to the combinator. Creating the array starts everything at once.

javascript
const wait = (ms, value, fail) =>
  new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));
const show = (p) => p.then((v) => 'ok ' + JSON.stringify(v), (e) => 'error ' + e.message);

(async () => {
  console.log('all        ->', await show(Promise.all([wait(30, 'a'), wait(10, 'b'), wait(20, 'c')])));
  console.log('all fails  ->', await show(Promise.all([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')])));
  console.log('race       ->', await show(Promise.race([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')])));
  console.log('any        ->', await show(Promise.any([wait(30, 'a'), wait(10, 'b', true), wait(20, 'c')])));
  console.log('any fails  ->', await show(Promise.any([wait(10, 'x', true), wait(20, 'y', true)])));
  console.log('allSettled ->', (await Promise.allSettled([wait(10, 'a'), wait(20, 'b', true)])).map((r) => r.status).join(','));
})();

Each line uses a different combinator on tasks of 10, 20 and 30 ms. Failures are turned into text so one line does not stop the script. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): all -> ok ["a","b","c"] all fails -> error b race -> error b any -> ok "c" any fails -> error All promises were rejected allSettled -> fulfilled,rejected

Key points

  • all keeps input order and rejects on the first failure.
  • race copies the first settlement, even a failure.
  • any ignores failures until one succeeds, else AggregateError.
  • allSettled never rejects.
  • None of them cancels the slower tasks.

Common mistakes

  • Expecting Promise.all results in finish order.
  • Believing that Promise.all cancels the other tasks.
  • Using race for a timeout without aborting the slow work.
  • Forgetting that any rejects with an AggregateError.
  • Starting tasks inside a loop that awaits each one and losing the parallelism.

Follow-ups

  • How do you implement a timeout with Promise.race and an AbortController?
  • How do you limit concurrency, since Promise.all starts everything at once?
  • What does the errors property of an AggregateError hold?

Tips

  • Walk through the timeline.
  • Say 'nothing is cancelled'.
  • Give one use case per combinator.