← Back to Node.js, page 10

nodejs-0196 · Medium mid

Implement Promise.all, Promise.allSettled, Promise.race and Promise.any from scratch. What edge cases matter?

All four take an iterable, convert each item with Promise.resolve, and settle by different rules. all resolves with the values in input order and rejects at the first rejection. allSettled never rejects and reports status objects. race settles with the first settled promise. any resolves with the first fulfilled value and rejects with an AggregateError when all reject. Edge cases: an empty input, plain values in the input, and keeping the input order.

Full answer

Common steps

  1. Convert the iterable to an array (Array.from), because it may be a generator or a Set.
  2. Wrap each item with Promise.resolve(item) so plain values and thenables work.
  3. Attach handlers with then and keep the results by index, not by completion order.

Rules per method

  • all: count fulfilled items. When the count reaches the length, resolve with the array of values. On the first rejection, reject with that reason. An empty input resolves at once with [].
  • allSettled: for each item store { status: 'fulfilled', value } or { status: 'rejected', reason }. Resolve when every item has settled. It never rejects (empty input gives []).
  • race: attach resolve and reject of the new promise to every item. The first one to settle wins. An empty input never settles (the promise stays pending forever).
  • any: resolve with the first fulfilled value. Collect the rejection reasons by index. When all items have rejected, reject with an AggregateError that has the errors array. An empty input rejects at once with an AggregateError.

Details

  • Later settlements are ignored automatically, because a promise can settle once.
  • Do not use push in the then handler for all, because completion order breaks the result order. Assign results[index].
  • The other promises keep running after all or race settles. These methods do not cancel anything.
javascript
const all = (items) => new Promise((resolve, reject) => {
  const list = Array.from(items), results = new Array(list.length);
  let remaining = list.length;
  if (remaining === 0) return resolve([]);
  list.forEach((item, i) => Promise.resolve(item).then((value) => { results[i] = value; if (--remaining === 0) resolve(results); }, reject));
});

const allSettled = (items) => all(Array.from(items, (item) => Promise.resolve(item).then(
  (value) => ({ status: 'fulfilled', value }),
  (reason) => ({ status: 'rejected', reason }),
)));

const race = (items) => new Promise((resolve, reject) => {
  for (const item of items) Promise.resolve(item).then(resolve, reject);
});

const any = (items) => new Promise((resolve, reject) => {
  const list = Array.from(items), errors = new Array(list.length);
  let remaining = list.length;
  if (remaining === 0) return reject(new AggregateError([], 'All promises were rejected'));
  list.forEach((item, i) => Promise.resolve(item).then(resolve, (reason) => {
    errors[i] = reason;
    if (--remaining === 0) reject(new AggregateError(errors, 'All promises were rejected'));
  }));
});

const later = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const failLater = (ms, message) => new Promise((_, reject) => setTimeout(reject, ms, new Error(message)));

(async () => {
  console.log('all order kept      :', await all([later(30, 'slow'), 'plain', later(5, 'fast')]));
  console.log('all empty           :', await all([]));
  console.log('all rejects first   :', await all([later(30, 'x'), failLater(5, 'early')]).catch((e) => e.message));
  console.log('allSettled          :', JSON.stringify(await allSettled([later(5, 1), failLater(10, 'no'), 3]), (k, v) => (v instanceof Error ? v.message : v)));
  console.log('race first settled  :', await race([later(30, 'slow'), later(5, 'fast')]));
  console.log('race first rejection:', await race([later(30, 'slow'), failLater(5, 'quick failure')]).catch((e) => e.message));
  console.log('any first fulfilled :', await any([failLater(5, 'a'), later(20, 'good'), later(40, 'late')]));
  const err = await any([failLater(5, 'a'), failLater(10, 'b')]).catch((e) => e);
  console.log('any all rejected    :', err.constructor.name, err.errors.map((e) => e.message));
  console.log('matches built-ins   :', JSON.stringify(await all([1, later(5, 2)])) === JSON.stringify(await Promise.all([1, later(5, 2)])));
})();

The helper functions use short timers with gaps of at least 15 ms, so the order is stable. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): all order kept : [ 'slow', 'plain', 'fast' ] all empty : [] all rejects first : early allSettled : [{"status":"fulfilled","value":1},{"status":"rejected","reason":"no"},{"status":"fulfilled","value":3}] race first settled : fast race first rejection: quick failure any first fulfilled : good any all rejected : AggregateError [ 'a', 'b' ] matches built-ins : true

Key points

  • Convert input items with Promise.resolve and keep results by index.
  • all rejects on the first rejection; allSettled never rejects.
  • race follows the first settled promise; any follows the first fulfilled one.
  • Empty input: all and allSettled resolve, any rejects, race stays pending.
  • Nothing is cancelled.

Common mistakes

  • Pushing results in completion order in all.
  • Forgetting Promise.resolve for plain values.
  • Expecting race([]) to settle.
  • Thinking the losing promises are cancelled.
  • Confusing any with race.

Follow-ups

  • How would you add a concurrency limit to all?
  • What does AggregateError contain?
  • How do you cancel the work of losing promises?

Tips

  • Give one rule per method.
  • Mention index-based results.
  • Mention empty input.