JavaScriptFundamental (ES6), part 2
Compare Promise.all, allSettled, any and race in JavaScript
24 all, allSettled, any and race on the same inputs
hardRun all four combinators over the same three promises, one of which rejects, and account for every difference. Then check the four empty-array cases, which do not agree either.
Stuck? Three hints, smallest first
- 1.
allwants every success;anywants one;allSettledwants the report;racewants the first, either way. - 2.
anyrejects with anAggregateErrorwhoseerrorsarray holds every reason. - 3. For the empty array the four disagree: two resolve, one rejects, one never settles at all.
const tills = () => [
Promise.resolve('till 1: ₦2,500'),
Promise.reject(new Error('till 2 offline')),
Promise.resolve('till 3: ₦4,000'),
];
const fromAll = await Promise.all(tills()).then((v) => ({ ok: v }), (e) => ({ error: e.message }));
const fromSettled = (await Promise.allSettled(tills())).map((r) =>
r.status === 'fulfilled' ? r.value : 'ERR: ' + r.reason.message
);
const fromAny = await Promise.any(tills());
const fromRace = await Promise.race(tills()).then((v) => v, (e) => 'rejected: ' + e.message);
const raceCanReject = await Promise.race([
Promise.reject(new Error('first to settle')),
Promise.resolve('a success that was available'),
]).then(() => 'resolved', (e) => e.message);
const allRejected = await Promise.any([Promise.reject(new Error('a')), Promise.reject(new Error('b'))])
.catch((e) => [e.constructor.name, e.errors.map((x) => x.message)]);
let emptyRace = 'still pending';
Promise.race([]).then(() => { emptyRace = 'settled'; });
for (let i = 0; i < 6; i++) await Promise.resolve();
console.log('all :', fromAll);
console.log('allSettled:', fromSettled);
console.log('any :', fromAny);
console.log('race :', fromRace);
console.log('empties : all', await Promise.all([]), ' race:', emptyRace);
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.
test('all rejects on the first failure and discards the successes it had', fromAll, { error: 'till 2 offline' });
test('allSettled reports every outcome instead', fromSettled, ['till 1: ₦2,500', 'ERR: till 2 offline', 'till 3: ₦4,000']);
test('any ignores rejections and takes the first success', fromAny, 'till 1: ₦2,500');
test('race takes the first to SETTLE, whichever way it went', fromRace, 'till 1: ₦2,500');
test('so race can reject even when a success was available', raceCanReject, 'first to settle');
test('any with nothing but failures gives an AggregateError listing them all', allRejected, ['AggregateError', ['a', 'b']]);
test('all of an empty array resolves at once', await Promise.all([]), []);
test('but any of an empty array rejects', await Promise.any([]).catch((e) => e.constructor.name), 'AggregateError');
test('and race of an empty array never settles at all', emptyRace, 'still pending');
Pick by the question you are asking. All of these must work is all — three parallel lookups feeding one page. Tell me how each one went is allSettled — a batch of independent uploads. Any one will do is any — the same query against three mirrors. Whatever happens first is race, and in practice that means a timeout.
The first assertion is the one that bites. all rejects the moment anything rejects, and the two successes that had already arrived are simply gone — you cannot recover them from the rejection. If partial success is useful to you, all is the wrong tool no matter how convenient the destructuring is.
race rejecting on the first settlement rather than the first success is the difference between it and any, and the fifth assertion is that in one line. Used as a timeout that is exactly right. Used as "fastest mirror wins" it is wrong, because the fastest mirror to fail wins too.
The empty cases are not a curiosity. all([]) and allSettled([]) resolve, any([]) rejects — vacuously, since no promise succeeded — and race([]) hangs for ever with no error and no warning. A list you built from a filter that happened to match nothing is how you meet that one.