JavaScriptFundamental (ES6), part 2
Why async generators are lazy in JavaScript
49 An async generator does nothing until you pull it
hardCompare two calls that look identical. Calling an async function runs its body immediately, up to the first await. Calling an async generator runs none of it. Prove both, then show that take(2) of five values produces exactly two, and that breaking out leaves the body unfinished.
Stuck? Three hints, smallest first
- 1. Track three things: whether the body started, how many values it produced, and whether it ran to the end.
- 2. Each
next()resumes the body until the nextyieldand no further. - 3.
breakin afor awaitcloses the iterator, so the body stops where it was suspended.
function readingsFrom(values) {
const state = { started: false, produced: 0, finished: false };
async function* generate() {
state.started = true;
for (const value of values) {
state.produced++;
await Promise.resolve(); // pretend the meter is slow
yield value;
}
state.finished = true;
}
return { readings: generate(), state };
}
async function take(n, iterable) {
const out = [];
for await (const value of iterable) {
out.push(value);
if (out.length === n) break;
}
return out;
}
const lazy = readingsFrom([24, 25, 26, 27, 28]);
const beforeAnyPull = [lazy.state.started, lazy.state.produced];
const eagerLog = [];
async function eager() {
eagerLog.push('async function body started');
await Promise.resolve();
eagerLog.push('and resumed later');
}
eager();
const eagerRanAtOnce = eagerLog.slice();
const first = await lazy.readings.next();
const afterOnePull = [lazy.state.started, lazy.state.produced, lazy.state.finished];
const partial = readingsFrom([24, 25, 26, 27, 28]);
const twoOfFive = await take(2, partial.readings);
const afterBreak = [partial.state.produced, partial.state.finished];
const whole = readingsFrom([24, 25, 26]);
const everything = [];
for await (const value of whole.readings) everything.push(value);
const afterDraining = [whole.state.produced, whole.state.finished];
const pastTheEnd = await whole.readings.next();
let endless = 0;
async function* forEver() {
while (true) {
endless++;
await Promise.resolve();
yield endless;
}
}
const firstThree = await take(3, forEver());
console.log('generator, before any pull:', beforeAnyPull);
console.log('async function, no pull :', eagerRanAtOnce);
console.log('after one next() :', afterOnePull, first.value);
console.log('take(2) of five :', twoOfFive, afterBreak);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('creating an async generator runs none of its body', beforeAnyPull, [false, 0]);
test('whereas calling an async function runs it at once, up to the first await', eagerRanAtOnce, ['async function body started']);
test('one next() starts the body and produces exactly one value', [afterOnePull, first.value], [[true, 1, false], 24]);
test('take(2) of five values produces two, not five', [twoOfFive, afterBreak[0]], [[24, 25], 2]);
test('and breaking out leaves the body unfinished, its last line unrun', afterBreak[1], false);
test('draining it fully does reach the end', afterDraining, [3, true]);
test('once done it stays done, and produces nothing more', [pastTheEnd.done, pastTheEnd.value === undefined, afterDraining[0]], [true, true, 3]);
test('so an endless generator is safe to take three values from', [firstThree, endless], [[1, 2, 3], 3]);
The first two assertions are the same syntax with opposite behaviour, and it is worth knowing which is which. async function starts working the moment you call it — exercise 40 makes that point from the error-handling side. async function* starts nothing: you get an object with a next() method and the body waits, having executed not one line. That is why an async generator can validate nothing at call time and why a bad argument surfaces on the first pull.
Laziness is per value, not per stream, which is what makes the fourth assertion possible: five values were available, two were asked for, and the meter was read exactly twice. Over a paged API that is two requests instead of ten; over an infinite sequence it is the difference between working and hanging.
The fifth is the cost of that design, and exercise 15 chases it further. A body suspended at a yield and then closed never runs its remaining lines — no completion log, no final flush, no finished = true — unless the cleanup sits in a finally, which break does honour. Anything a producer must do on the way out belongs there and nowhere else.