Sub topic 11
Delegating to Other Iterables with yield*
This chapter assumes you can write an async generator with async function* and consume one with for await...of. It also assumes you know how return() and finally behave when a loop exits early. You will learn how yield* lets one async generator hand control to another iterable, and what it forwards along the way.
What yield* does
yield* delegates to another iterable. The outer generator pauses its own work and passes through every value the inner iterable produces. When the inner iterable finishes, the outer generator continues from the line after yield*.
In an async generator, yield* accepts two kinds of source:
| Source | How it is iterated |
|---|---|
| Async iterable (has `Symbol.asyncIterator`) | Each `next()` promise is awaited |
| Sync iterable (array, Set, sync generator) | Wrapped automatically, and each value is awaited |
Each value from a sync source is awaited, so an array of promises yields the resolved values, not the promises.
async function* letters() {
yield 'a';
yield 'b';
return 'letters done';
}
async function* combined() {
yield 0;
const result = yield* letters();
console.log('inner returned:', result);
yield* [1, 2];
yield* [Promise.resolve('p')];
}
async function main() {
for await (const v of combined()) {
console.log(v);
}
}
main();
// 0, a, b, inner returned: letters done, 1, 2, pThis example also shows that yield* is an expression. Its value is whatever the inner generator returns. The returned value is not yielded to the consumer. Only the outer generator sees it.
What gets forwarded
yield* does more than copy values. It connects the consumer straight to the inner iterator, so all three iterator methods pass through:
next(x)goes to the inner iterator'snext(x).throw(err)goes to the inner iterator'sthrow(err), so the inner generator can catch it.return()goes to the inner iterator'sreturn(), so the inner generator'sfinallyruns first.
That last point matters for cleanup. If the consumer breaks out of the loop while delegation is active, both generators clean up, inner first:
async function* inner() {
try {
yield 1;
yield 2;
} finally {
console.log('inner cleanup');
}
}
async function* outer() {
try {
yield* inner();
yield 3;
} finally {
console.log('outer cleanup');
}
}
async function main() {
for await (const v of outer()) {
console.log(v);
break;
}
}
main();
// 1, inner cleanup, outer cleanupyield* versus a manual loop
You can write delegation by hand with for await (const x of source) yield x;. That works, and it still cleans up the inner source when you break. But it differs from yield* in two ways:
- The inner generator's
returnvalue is lost. A manual loop gives you no way to read it. - A
throw()call from the consumer is not passed to the inner iterator. It is raised at the outeryield, and the inner source is then closed withreturn().
Use yield* when you want transparent delegation. Use a manual loop when you need to inspect or change each item, as a filter does.
Common mistakes
- Expecting the return value in the loop.
for await...ofignores the value that comes withdone: true, so'letters done'never reaches the consumer. Capture it withconst r = yield* .... - Forgetting the
*.yield letters()yields the generator object itself as a single value. It does not delegate. - Delegating to a string by accident. Strings are sync iterables, so
yield* 'abc'yields'a','b','c'. That may not be what you meant.
Exercise
Write an async generator concat(...sources) that yields every value from each source in order. Each source may be an async iterable or an array. What does for await (const v of concat([1, 2], letters())) print, using letters from this chapter?
Show answer
async function* concat(...sources) { for (const s of sources) { yield* s; } }. A plain for...of works for the outer loop because sources is an ordinary array. It prints 1, 2, a, b. The return value 'letters done' is not printed, because yield* hands it to concat and not to the consumer.
Exercise
In the inner/outer cleanup example, suppose the loop breaks when v is 3 instead of on the first value. What is printed?
Show answer
1, 2, inner cleanup, 3, outer cleanup. Here inner finishes normally and its finally runs before yield 3. The break at 3 then triggers only outer's finally.