Sub topic 11
Delegating to Other Iterables with yield*
An async generator often needs to hand over part of its work to another sequence. It might replay the items from another generator, add a fixed list of defaults, or read one page of results before moving on. You could write a for await...of loop that re-yields every value. JavaScript also offers a shorter form, yield*, which delegates to another iterable and forwards the whole iteration protocol to it.
This chapter assumes you already know how async generators produce values with async function* and yield, how for await...of consumes them, and how return() and finally behave when a loop exits early. All examples run in Node.js 18 or later, or in a modern browser console.
What yield* Does
Inside an async generator, yield* expr does three things:
- It gets an iterator from
expr. It first looks forSymbol.asyncIterator. If that is missing, it falls back toSymbol.iteratorand wraps the sync iterator so each value is awaited. - It passes every value from that iterator to the outer generator's consumer, one at a time. The outer generator stays paused at the
yield*until the inner iterator finishes. - When the inner iterator reports
done: true, theyield*expression evaluates to the inner iterator's finalvalue. For a generator, that is the value itreturned.
Here is a generator that joins three different kinds of sources:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* letters() {
await sleep(50);
yield 'a';
await sleep(50);
yield 'b';
}
async function* everything() {
yield* letters(); // async iterable
yield* [1, Promise.resolve(2)]; // sync iterable; promises are awaited
yield* 'xy'; // strings are iterable too
}
async function main() {
for await (const value of everything()) {
console.log(value); // a, b, 1, 2, x, y
}
}
main();The consumer gets 2 and not a Promise. When an async generator delegates to a sync iterable, each value goes through the same awaiting step that a plain yield applies. So an array of promises comes out as resolved values.
How Calls Are Forwarded
yield* goes beyond a loop that re-yields values. While the outer generator is delegating, every method the consumer calls on the outer generator goes to the inner iterator:
| Consumer calls | While delegating, yield* does |
|---|---|
| `outer.next(v)` | Calls `inner.next(v)` and passes its result on |
| `outer.throw(err)` | Calls `inner.throw(err)` if it exists. Otherwise it closes the inner iterator and throws a TypeError |
| `outer.return(v)` | Calls `inner.return(v)` if it exists, then finishes the outer generator |
The sequence diagram below shows a normal run, including where the return value ends up.
Using the Return Value
A for await...of loop ignores the value in the final { done: true } result. yield* keeps it, which lets an inner generator send information back to the outer one. Pagination is a common use: the inner generator yields one page's items and returns the next page number.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Simulates fetching one page; returns the next page number or null.
async function* readPage(page) {
await sleep(50);
yield `page${page}-item1`;
yield `page${page}-item2`;
return page < 3 ? page + 1 : null;
}
async function* readAllPages() {
let page = 1;
while (page !== null) {
page = yield* readPage(page);
}
}
async function main() {
for await (const item of readAllPages()) {
console.log(item);
}
}
main(); // page1-item1, page1-item2, page2-item1, ... page3-item2The consumer only sees the six items. The page numbers move between the two generators and never reach the loop.
Early Exit Reaches the Inner Generator
If the consumer leaves the loop with break, return, or an exception, for await...of calls return() on the outer generator. Because the outer generator is paused inside yield*, that call goes to the inner generator first. The inner generator's finally runs, and then the outer one's.
async function* inner() {
console.log('inner: open');
try {
yield 1;
yield 2;
} finally {
console.log('inner: close');
}
}
async function* outer() {
console.log('outer: open');
try {
yield* inner();
yield 3;
} finally {
console.log('outer: close');
}
}
async function main() {
for await (const n of outer()) {
console.log(n);
if (n === 1) break;
}
}
main();
// outer: open
// inner: open
// 1
// inner: close
// outer: closeCleanup runs from the inside out, the same order in which nested try blocks unwind. Resources the inner generator opened are released before the outer generator's cleanup runs.
Errors Travel Both Ways
Errors cross the delegation boundary in two directions.
An error thrown inside the inner generator comes out of the yield* expression in the outer generator. If you wrap yield* in try/catch, the outer generator can recover and keep yielding:
async function* unreliable() {
yield 'first';
throw new Error('source failed');
}
async function* withFallback() {
try {
yield* unreliable();
} catch (err) {
console.log('outer caught:', err.message);
yield 'fallback';
}
}
async function main() {
for await (const value of withFallback()) {
console.log(value);
}
}
main();
// first
// outer caught: source failed
// fallbackThe other direction is an error injected by the consumer with throw(). It goes to the inner generator, which gets the first chance to handle it:
async function* inner() {
try {
yield 1;
yield 2;
} catch (err) {
console.log('inner caught:', err.message);
yield 'recovered';
}
}
async function* outer() {
yield* inner();
}
async function main() {
const it = outer();
console.log(await it.next()); // { value: 1, done: false }
console.log(await it.throw(new Error('boom'))); // inner caught: boom
// { value: 'recovered', done: false }
console.log(await it.next()); // { value: undefined, done: true }
}
main();Most code never calls throw() by hand. Still, this forwarding is the main thing a hand-written re-yield loop does differently, as the next section shows.
yield* Compared with a Manual Loop
You can get the same values with a loop:
async function* outerManual(source) {
for await (const item of source) {
yield item;
}
}For the common case, where the consumer calls next() and sometimes breaks, the two forms behave the same. Breaking out of the consumer's loop still closes the inner source, because the outer generator's for await...of exits and calls return() on its source. The forms differ at the edges:
| Aspect | `yield* source` | `for await` + `yield` |
|---|---|---|
| Values forwarded | Yes | Yes |
| `return()` reaches source | Yes, forwarded directly | Yes, through the loop's exit |
| `throw()` reaches source | Yes, source can catch it | No, it is raised at the outer `yield` and the source is closed with `return()` |
| Source's return value | Becomes the result of `yield*` | Discarded |
| Per-item logic (filter, map, count) | Not possible | Easy to add in the loop body |
Use yield* when you want to pass a sequence through unchanged, especially when you need its return value. Use a loop when you need to look at or change each item. That is the building block for the filter and map stages in the next chapter.
Common Mistakes
Forgetting the asterisk
yield inner() yields the generator object as a single value. It does not yield the items inside it.
async function* inner() {
yield 1;
}
async function* wrong() {
yield inner(); // yields an AsyncGenerator object
}
async function main() {
for await (const v of wrong()) {
console.log(typeof v, Object.prototype.toString.call(v));
// object [object AsyncGenerator]
}
}
main();If your loop prints [object AsyncGenerator] or {}, look for a missing *.
Using yield* on an async source from a sync generator
A regular function* can only delegate to sync iterables. Async generator objects have Symbol.asyncIterator but no Symbol.iterator, so delegating to one throws:
async function* source() {
yield 1;
}
function* syncOuter() {
yield* source();
}
try {
[...syncOuter()];
} catch (err) {
console.log(err.constructor.name); // TypeError
}The fix is to make the outer function async function* and consume it with for await...of.
Delegating to something that is not iterable
yield* on a plain object, a number, null, or a single Promise throws a TypeError. A Promise is not iterable. To yield the resolved value of one Promise, use plain yield, which awaits it for you inside an async generator.
Iterating a string by accident
Strings are iterable, so yield* 'hello' yields five characters. If a function sometimes returns a string and sometimes an array, yield* turns the string into characters without any error. Check the type, or wrap single values in an array first.
Delegating to an already used iterator
Delegating to an iterator, as opposed to an iterable that creates a new iterator each time, continues from wherever that iterator stopped. A generator object that has already finished yields nothing. If you call yield* gen twice on the same generator object, the second call produces no values and evaluates to undefined.
Exercises
Exercise
An async generator runs const total = yield* counter();, where counter is an async generator that yields 'x' and 'y' and then runs return 2;. What does a for await...of loop over the outer generator print if it logs each value, and what is stored in total?
Show answer
The loop prints 'x' and 'y'. The return value 2 never reaches the loop, because for await...of ignores the value of the final done result. total is 2, because yield* evaluates to the inner generator's return value.
Exercise
The outer generator runs yield* inner() inside try/finally, and inner also has a finally block. The consumer breaks after the first value. In what order do the two finally blocks run, and why?
Show answer
The inner finally runs first, then the outer one. The loop calls return() on the outer generator. Because the outer generator is paused inside yield*, the call goes to inner.return(), which runs inner's finally. After the inner generator completes, the outer generator unwinds and runs its own finally.
Exercise
Rewrite async function* passThrough(src) { for await (const x of src) yield x; } with yield*, and name one behavior that changes.
Show answer
async function* passThrough(src) { yield* src; }. The values produced are the same. With yield, a call to passThrough(...).throw(err) is forwarded to the source's throw(), so the source can catch it. In the loop version, the error is raised at the outer yield and the source is just closed with return(). yield also makes the source's return value available, which the loop discards.