JavaScriptFundamental (ES6), part 2
Handle rejected promises in for await...of in JavaScript
16 A rejection inside for await ends the loop
fairLoop with for await over an array containing one rejected promise. Show that the loop throws and stops, that the values after it are never read, and write the version that reports every outcome instead.
Stuck? Three hints, smallest first
- 1. The rejection surfaces at the
await, so an ordinarytry/catcharound the loop catches it. - 2. Once it throws, the loop is over: nothing after the failing element is visited.
- 3. To survive it, do the awaiting yourself inside the loop body, one
tryper item.
const mixed = [
Promise.resolve('till 1: ₦2,500'),
Promise.reject(new Error('till 2 offline')),
Promise.resolve('till 3: ₦4,000'),
];
const collected = [];
let caught = '';
try {
for await (const line of mixed) collected.push(line);
} catch (err) {
caught = err.message;
}
// One try per item, so a failure is data rather than an exit.
const settledEach = async (promises) => {
const out = [];
for (const p of promises) {
try { out.push({ status: 'fulfilled', value: await p }); }
catch (err) { out.push({ status: 'rejected', reason: err.message }); }
}
return out;
};
const everyOutcome = await settledEach(mixed);
console.log('got before the failure:', collected);
console.log('caught :', caught);
console.log('every outcome :', everyOutcome.map((r) => r.status));
Output
7 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 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the loop stops at the first rejection', collected, ['till 1: ₦2,500']);
test('and the rejection surfaces as a throw', caught, 'till 2 offline');
test('so the third value is never read', collected.length, 1);
test('handling each one keeps the loop going', everyOutcome.map((r) => r.status), ['fulfilled', 'rejected', 'fulfilled']);
test('and records why the middle one failed', everyOutcome[1].reason, 'till 2 offline');
test('a settled promise can be awaited again, so nothing was consumed', await mixed[0], 'till 1: ₦2,500');
test('a plain value in the list passes straight through', await settledEach(['plain', 7]).then((r) => r.map((x) => x.value)), ['plain', 7]);
for await is a loop with an await in it, so a rejection behaves exactly like a throw inside a for body: the loop ends and the exception propagates. That is usually right, and it is the same all-or-nothing decision Promise.all makes — which is why exercise 24 puts the four combinators side by side.
The interesting part is what you lose. collected holds the first result and the third is never read, even though its promise had already resolved before the loop began. The work was done; the value was thrown away with the loop.
settledEach is Promise.allSettled's behaviour written out by hand, and writing it out shows what it costs: the results are shaped, not raw, so every caller has to branch on status. That is the trade. Prefer the throwing loop when any failure means the whole operation is void, and the settled shape when each item stands alone — a batch upload of receipts, say, where four of five landing is a useful outcome.