← Back to JavaScript, page 5

javascript-0085 · Hard senior

Implement Promise.all, Promise.allSettled, Promise.race, and Promise.any from scratch. What details do correct versions handle?

Each combinator accepts any iterable, converts every item with Promise.resolve so plain values work, and settles a new promise. all keeps results in input order and rejects at the first failure, allSettled never rejects, race follows the first settlement, and any rejects with an AggregateError only when all fail. Empty input needs special handling, and a counter, not result length, tracks completion.

Full answer

These functions are a favorite exercise because they test promises, closures, and edge cases together.

Common structure: return new Promise((resolve, reject) => { ... }), turn the input into an array with Array.from(iterable), and wrap each item with Promise.resolve(item) so plain values and thenables work.

all: keep a results array and a remaining counter. When item i fulfills, store results[i] = value (the index keeps input order, even when promises finish in another order), decrease the counter, and resolve when it reaches zero. Any rejection rejects the outer promise immediately. An empty input must resolve with [] at once, since no callback will ever run to trigger the resolve. Using results.length instead of a counter is a classic bug, because assigning to a high index makes the length jump early.

allSettled: the same shape, but both outcomes store an object, { status: 'fulfilled', value } or { status: 'rejected', reason }, and the promise never rejects.

race: attach the outer resolve and reject to every item. The first to settle wins, and later calls are ignored because a promise settles once. An empty input never settles.

any: the opposite of all. The first fulfillment resolves. Collect rejection reasons by index, and when all have rejected, reject with new AggregateError(errors, 'All promises were rejected'). An empty input rejects right away.

Other details: if the iterable itself throws while iterating, the returned promise should reject instead of throwing synchronously, and the executor already handles that when the code runs inside it. None of these cancel the other promises.

javascript
const promiseAll = (iterable) =>
  new Promise((resolve, reject) => {
    const items = Array.from(iterable);
    const results = new Array(items.length);
    let remaining = items.length;
    if (remaining === 0) return resolve(results);
    items.forEach((item, index) => {
      Promise.resolve(item).then((value) => {
        results[index] = value;
        if (--remaining === 0) resolve(results);
      }, reject);
    });
  });

const promiseAllSettled = (iterable) =>
  new Promise((resolve) => {
    const items = Array.from(iterable);
    const results = new Array(items.length);
    let remaining = items.length;
    if (remaining === 0) return resolve(results);
    const done = (index, outcome) => {
      results[index] = outcome;
      if (--remaining === 0) resolve(results);
    };
    items.forEach((item, index) => {
      Promise.resolve(item).then(
        (value) => done(index, { status: 'fulfilled', value }),
        (reason) => done(index, { status: 'rejected', reason })
      );
    });
  });

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

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

const delay = (ms, value, fail = false) =>
  new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));

const describe = (promise) =>
  promise
    .then((value) => ({ fulfilled: value }), (error) => ({ rejected: error instanceof AggregateError ? error.errors : error }))
    .then((outcome) => JSON.stringify(outcome, (key, value) => (value instanceof Error ? value.message : value)));

const cases = [
  ['all, mixed values', promiseAll, Promise.all, () => [delay(30, 'slow'), 'plain', delay(5, 'fast')]],
  ['all, one rejects', promiseAll, Promise.all, () => [delay(5, 'ok'), delay(10, 'bad', true)]],
  ['all, empty', promiseAll, Promise.all, () => []],
  ['allSettled', promiseAllSettled, Promise.allSettled, () => [delay(5, 'ok'), delay(10, 'bad', true)]],
  ['race', promiseRace, Promise.race, () => [delay(20, 'slow'), delay(5, 'fast')]],
  ['any, one succeeds', promiseAny, Promise.any, () => [delay(5, 'x', true), delay(15, 'winner')]],
  ['any, all fail', promiseAny, Promise.any, () => [delay(5, 'x', true), delay(10, 'y', true)]],
  ['any, empty', promiseAny, Promise.any, () => []],
];

(async () => {
  for (const [name, mine, native, makeInput] of cases) {
    const mineResult = await describe(mine(makeInput()));
    const nativeResult = await describe(native.call(Promise, makeInput()));
    console.log(name.padEnd(18), mineResult === nativeResult ? 'matches native' : 'DIFFERS', mineResult);
  }

  console.log(await promiseAll(new Set([Promise.resolve(1), 2])));
  const throwing = promiseAll((function* () { yield 1; throw new Error('iterator failed'); })());
  console.log(await describe(throwing));
})();

Run with Node.js v24.22.1 as js-85.js; two runs gave identical output. Output: all, mixed values matches native {"fulfilled":["slow","plain","fast"]} all, one rejects matches native {"rejected":"bad"} all, empty matches native {"fulfilled":[]} allSettled matches native {"fulfilled":[{"status":"fulfilled","value":"ok"},{"status":"rejected","reason":"bad"}]} race matches native {"fulfilled":"fast"} any, one succeeds matches native {"fulfilled":"winner"} any, all fail matches native {"rejected":["x","y"]} any, empty matches native {"rejected":[]} [ 1, 2 ] {"rejected":"iterator failed"}

Key points

  • Wrap every item with Promise.resolve and return a new Promise.
  • all: results by index plus a remaining counter; empty input resolves immediately.
  • allSettled stores status objects and never rejects.
  • race passes resolve and reject to every item; any collects errors and rejects with AggregateError.
  • Do not use results.length to detect completion.

Common mistakes

  • Using results.length to decide that all promises finished.
  • Forgetting the empty-input case for all and any, which leaves the promise pending forever.
  • Pushing results in completion order instead of storing them by index.
  • Not wrapping items with Promise.resolve, which breaks plain values and thenables.

Follow-ups

  • How would you implement a version of all with a concurrency limit?
  • Why does race with an empty array never settle?
  • How would you make allSettled report timing for each promise?

Tips

  • Describe the index plus counter design before writing code.
  • Mention the empty-input edge case without being asked.
  • Compare your results against the built-in functions to show your tests.