Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Promise.all vs allSettled vs any vs race in JavaScript

89 all, allSettled, any and race, judged on a rejection

hard

Ask three Lagos markets for a quote at the same time, where one of them fails, and put all four combinators through it. Show what each one gives back, what happens to the losers, what Promise.any throws when everybody fails, and what each does with an empty list.

Stuck? Three hints, smallest first
  1. 1. Order things with microtask ticks rather than timers: chain .then a few times to make one job settle after another.
  2. 2. all rejects on the first rejection, allSettled never rejects, any wants one success, race takes the first settlement of either kind.
  3. 3. For the empty list, do not await Promise.race([]). Attach a handler that sets a flag, drain some ticks, then assert the flag never changed.

The answer

const after = (ticks, value) => {
  let p = Promise.resolve();
  for (let i = 0; i < ticks; i++) p = p.then((v) => v);
  return p.then(() => value);
};

const finished = [];
const quote = (market, ticks) =>
  after(ticks, market).then((name) => {
    finished.push(name);
    return name;
  });
const outOfStock = (market, ticks) =>
  after(ticks, market).then(() => {
    finished.push(market + ' failed');
    throw new Error(market + ' is out of stock');
  });

let allError;
try {
  await Promise.all([quote('Balogun', 1), outOfStock('Oyingbo', 3), quote('Mile12', 9)]);
} catch (error) {
  allError = error.message;
}
const atRejection = [...finished];
await after(20, null);
const afterwards = [...finished];

const settled = (await Promise.allSettled([quote('Ketu', 1), outOfStock('Ojota', 2)])).map((one) => [
  one.status,
  one.status === 'fulfilled' ? one.value : one.reason.message,
]);

const anyValue = await Promise.any([outOfStock('Agege', 1), quote('Yaba', 4), quote('Epe', 8)]);

let aggregate;
try {
  await Promise.any([outOfStock('Ajah', 1), outOfStock('Ikorodu', 2)]);
} catch (error) {
  aggregate = [error.constructor.name, error.errors.map((e) => e.message)];
}

const raced = await Promise.race([quote('Surulere', 5), quote('Lekki', 1)]);
let racedError;
try {
  await Promise.race([outOfStock('Badagry', 1), quote('Apapa', 5)]);
} catch (error) {
  racedError = error.message;
}

const emptyAll = await Promise.all([]);
const emptySettled = await Promise.allSettled([]);
let emptyAny;
try {
  await Promise.any([]);
} catch (error) {
  emptyAny = [error.constructor.name, error.errors.length];
}

let raceEmptyDone = false;
Promise.race([]).then(() => { raceEmptyDone = true; }, () => { raceEmptyDone = true; });
await after(30, null);
const raceEmptyPending = raceEmptyDone === false;

const inOrder = await Promise.all([quote('slow', 9), quote('fast', 1)]);

console.log('all       :', allError, '| at the rejection:', atRejection);
console.log('losers    :', afterwards);
console.log('allSettled:', settled, '| any:', anyValue);
console.log('all failed:', aggregate, '| race:', raced, racedError);
console.log('empty     :', emptyAll, emptySettled, emptyAny, '| race([]) pending:', raceEmptyPending);
console.log('order     :', inOrder);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('all rejects with the reason of the first rejection to happen', allError, 'Oyingbo is out of stock');
test('the losers are not cancelled: the slow one finishes long afterwards', [atRejection, afterwards], [['Balogun', 'Oyingbo failed'], ['Balogun', 'Oyingbo failed', 'Mile12']]);
test('allSettled never rejects; every outcome comes back labelled', settled, [['fulfilled', 'Ketu'], ['rejected', 'Ojota is out of stock']]);
test('any ignores rejections and resolves with the first success', anyValue, 'Yaba');
test('if every one fails, any throws an AggregateError holding all the reasons', aggregate, ['AggregateError', ['Ajah is out of stock', 'Ikorodu is out of stock']]);
test('race takes the first to settle, and a rejection counts as settling', [raced, racedError], ['Lekki', 'Badagry is out of stock']);
test('of an empty list, all and allSettled resolve at once and any rejects at once', [emptyAll, emptySettled, emptyAny], [[], [], ['AggregateError', 0]]);
test('but race of an empty list is pending for ever, so never pass it one', raceEmptyPending, true);
test('all keeps the order you passed in, not the order things finished', inOrder, ['slow', 'fast']);

Choose by what you want to happen to the failures. all is for a set where any failure ruins the answer: it rejects with the first reason and gives you nothing else, and the values it did collect are lost. allSettled is for a batch where each row stands alone — it always fulfils, with a { status, value } or { status, reason } for every entry, which is what you want for a report of twenty uploads where three failed. any is for redundancy: several sources, first usable answer wins, and it only fails if they all do. race is for whichever finishes first, including a timeout you deliberately put in the list.

None of them cancels anything. That is the assertion above worth staring at: Promise.all rejected, and the third market still finished its work and pushed its name afterwards. A promise is a handle on work already in flight, not a controller of it, so the losers of a race keep running, their side effects still happen, and their rejections still need somewhere to go. Cancellation needs an AbortController threaded through the work itself.

The empty cases are asymmetric and the last one is a real hang. all([]) and allSettled([]) fulfil immediately, any([]) rejects immediately with an AggregateError whose errors array is empty, and race([]) never settles at all — so a race over a filtered list that turned out empty is a request that hangs for ever with no error to show for it. Two smaller notes: all preserves input order regardless of completion order, so destructuring the result is safe; and AggregateError keeps the reasons on .errors rather than in .message, which is where people look first.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.