JavaScriptFundamental (ES6), part 1
for await...of and async generators in JavaScript
88 for await...of, and who closes the generator
fairRead a list of promises with for await...of, then write an async function* that awaits inside itself and yields the result. Prove the producer and the loop body take turns, find out what a break does to a generator holding a finally, and catch a rejection that lands in the middle of the loop.
Stuck? Three hints, smallest first
- 1.
for await (const x of things)awaits every value on its way out, soxis never a promise. - 2. An
async function*may useawaitandyieldin the same body. Wrap its loop intry { ... } finally { ... }and watch when the finally runs. - 3. A
breakout of the loop callsreturn()on the iterator, and a rejected value throws at the point of theawait, sotryaround the whole loop catches it.
const settle = (value) => Promise.resolve(value); // stands in for one request
const arrived = [];
for await (const name of ['Adaeze', 'Chinedu', 'Yetunde'].map(settle)) arrived.push(name);
let closes = 0;
async function* riders(names) {
try {
for (const name of names) {
const checked = await settle(name.toUpperCase());
yield checked;
}
} finally {
closes++; // runs however the loop ends
}
}
const upper = [];
for await (const name of riders(['adaeze', 'chinedu'])) upper.push(name);
const closesAfterFull = closes;
const partial = [];
for await (const name of riders(['adaeze', 'chinedu', 'yetunde'])) {
partial.push(name);
if (partial.length === 1) break;
}
const closesAfterBreak = closes;
const woven = [];
async function* two() {
woven.push('yielded a');
yield 'a';
woven.push('yielded b');
yield 'b';
}
for await (const value of two()) woven.push('body ' + value);
const seen = [];
let loopError;
try {
for await (const one of [settle('ok'), Promise.reject(new Error('rider offline')), settle('never read')]) {
seen.push(one);
}
} catch (error) {
loopError = error.message;
}
const plainValues = [];
for await (const kobo of [12000, 25000]) plainValues.push(kobo);
const it = riders(['bola'])[Symbol.asyncIterator]();
const isOwnIterator = it[Symbol.asyncIterator]() === it;
const step = await it.next();
const end = await it.next();
const byHand = [step.value, step.done, end.done, end.value === undefined];
console.log('promises :', arrived, '| plain values:', plainValues);
console.log('generator :', upper, '| closes after a full loop:', closesAfterFull);
console.log('break :', partial, '| closes after a break:', closesAfterBreak);
console.log('interleave:', woven);
console.log('rejection :', seen, loopError, '| by hand:', byHand, isOwnIterator);
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('for await over promises hands you values, in order, never promises', arrived, ['Adaeze', 'Chinedu', 'Yetunde']);
test('an async generator may await inside and yield the result', upper, ['ADAEZE', 'CHINEDU']);
test('running the loop out closes the generator, so its finally runs', closesAfterFull, 1);
test('and a break closes it too, by calling return on the iterator', [partial, closesAfterBreak], [['ADAEZE'], 2]);
test('producer and body take turns; nothing is computed ahead of time', woven, ['yielded a', 'body a', 'yielded b', 'body b']);
test('a rejected value throws at the await, so try around the loop catches it', [seen, loopError], [['ok'], 'rider offline']);
test('and the loop stops there, never reaching the third entry', seen.length, 1);
test('for await is happy with plain values too, promise or not', plainValues, [12000, 25000]);
test('the loop is only calling next() and unwrapping what comes back', byHand, ['BOLA', false, true, true]);
for await...of is a sequential reader, and that is the whole point of it. Each turn awaits one value before the body runs, so three requests read this way take the sum of their times, not the maximum. When the items are independent and you want them at once, that is Promise.all; when each one depends on the last, or the source produces them one at a time like a paged API, for await is the right shape. Note that it accepts plain values as well, so a list that is only sometimes asynchronous still works.
An async function* is the producing half: await for the fetching, yield for the handing over, and nothing runs until the consumer asks. The interleaved trace above is the evidence — the second value is not produced while the body is still working on the first.
The finally is the part worth internalising. A break, a return or a thrown error inside the loop calls return() on the iterator, which resumes the generator at its suspension point purely to run the cleanup. So a connection opened before the loop and closed in a finally is closed even when the consumer walks away early. What it does not do is unsubscribe from work already in flight: a rejection ends the loop, and any promise created before it was created eagerly and is still running, which is why a stray Promise.reject in a list can leave an unhandled rejection behind if the loop never reaches it.