Sub topic 3
Sending Values In, Cleanup, Laziness, and Async Generators
This chapter assumes you know generator basics (function*, yield, next()), plus promises and async/await.
Sending Values In: next(value), throw(), and return()
A paused yield is an expression. The argument you pass to next(value) becomes its result. The first next() only starts the generator, so any value passed to it is discarded.
function* runningTotal() {
let total = 0;
while (true) {
const n = yield total;
total += n;
}
}
const acc = runningTotal();
console.log(acc.next()); // { value: 0, done: false } (starts the generator)
console.log(acc.next(5)); // { value: 5, done: false }
console.log(acc.next(10)); // { value: 15, done: false }
console.log(acc.return(99)); // { value: 99, done: true }throw(err) raises err at the paused yield, where a try...catch inside the generator can handle it. return(v) finishes the generator early.
Cleaning Up with try...finally
When a consumer leaves for...of early through break, return, or an exception, it calls the generator's return(). That call runs any pending finally block.
function* lines() {
console.log('open');
try {
yield 'line 1';
yield 'line 2';
} finally {
console.log('close');
}
}
for (const line of lines()) {
console.log(line);
break;
}
// open, line 1, closeLazy Pipelines and Iterator Helpers
Generators compute values only when asked. That makes infinite sources safe, as long as something downstream limits how many values it pulls. The ES2025 iterator helpers on Iterator.prototype chain lazily:
function* naturals() {
let n = 0;
while (true) yield n++;
}
// Iterator helpers (ES2025); check that your target runtime supports them
const result = naturals()
.filter(n => n % 2 === 0)
.map(n => n * 10)
.take(3)
.toArray();
console.log(result); // [ 0, 20, 40 ]Async Iteration and Async Generators
An async function* can await between yields. You consume it with for await...of, which waits for each result before running the loop body. Async generators turn paginated APIs into one flat stream, and each page is fetched only when the consumer needs it:
async function* paginate(fetchPage) {
let page = 1;
while (true) {
const items = await fetchPage(page);
if (items.length === 0) return;
yield* items;
page++;
}
}
const pages = { 1: ['a', 'b'], 2: ['c'] };
const fetchPage = async page => pages[page] ?? [];
(async () => {
for await (const item of paginate(fetchPage)) {
console.log(item); // a, b, c
}
})();Pitfalls and Best Practices
| Pitfall | Fix |
|---|---|
| Reusing a generator object; the second pass yields nothing | Call the generator function again, or wrap it in an iterable |
| Expecting `for...of` or spread to include the `return` value | Use `yield` for every value the consumer should see |
| Leaking resources on early exit | Put cleanup in `finally` |
| Passing data to the first `next()` | Prime the generator with an empty `next()` first |
Exercise
Given const gen = (function* () { yield 1; yield 2; })();, what do [...gen] and then a second [...gen] produce, and why?
Show answer
The first spread gives [ 1, 2 ] and the second gives []. A generator object is its own one-shot iterator, so once it finishes it stays finished.
Exercise
In runningTotal, what does acc.next(7) return if it is the very first call?
Show answer
{ value: 0, done: false }. The first next() only runs the generator up to the first yield, so the 7 is discarded.