Sub topic 4
Producing Async Sequences with async function*
The previous chapters showed how to consume async iterables with for await...of. This chapter covers the producer side. Writing an async iterator object by hand means managing next(), promises, and { value, done } objects yourself. An async generator function writes that object for you. This chapter assumes you know ordinary (sync) generators with function* and yield, promises and async/await, and the async iteration protocol from the earlier chapters.
The syntax and what it gives you
An async generator function is declared with async function*. Inside its body you can use both await and yield:
awaitpauses the body until a promise settles, as in any async function.yieldhands one value to the consumer and pauses the body until the consumer asks for the next one.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* countdown(from) {
for (let i = from; i > 0; i--) {
await sleep(100);
yield i;
}
}
async function main() {
for await (const n of countdown(3)) {
console.log(n); // 3, 2, 1, about 100 ms apart
}
}
main();Calling countdown(3) does not run any of the body. It returns an async generator object right away. That object has three properties that matter:
- It has a
next()method that returns a promise of{ value, done }, so it is an async iterator. - Its
[Symbol.asyncIterator]()method returns the object itself, so it is also an async iterable. This is why you can pass it straight tofor await...of. - It also has
return()andthrow()methods. Later chapters on errors and early exit cover these.
You can declare async generators in several forms:
// Declaration
async function* a() { yield 1; }
// Expression
const b = async function* () { yield 2; };
// Object or class method
const obj = {
async *items() { yield 3; }
};
class Feed {
async *[Symbol.asyncIterator]() { yield 4; }
}There is no async generator arrow function. async* () => {} is a syntax error.
The class Feed form is worth remembering. Defining [Symbol.asyncIterator] as an async generator method makes every instance of the class async iterable, and you write no iterator bookkeeping at all.
Lazy execution, step by step
To see exactly when the body runs, drive the generator by hand with next() instead of a loop:
async function* letters() {
console.log('body started');
yield 'a';
console.log('resumed after a');
yield 'b';
console.log('resumed after b');
return 'finished';
}
async function main() {
const gen = letters();
console.log('generator created');
console.log(await gen.next());
console.log(await gen.next());
console.log(await gen.next());
console.log(await gen.next());
}
main();The output is:
generator created
body started
{ value: 'a', done: false }
resumed after a
{ value: 'b', done: false }
resumed after b
{ value: 'finished', done: true }
{ value: undefined, done: true }Each next() call does the following:
- It resumes the body from where it last paused. The first call starts it from the top.
- It runs the body until it reaches the next
yield, areturn, the end of the function, or a thrown error. - It resolves the returned promise with
{ value, done: false }for ayield, or{ value, done: true }for areturnor the end of the function.
After the body has finished, every later next() resolves to { value: undefined, done: true }. A generator object is single-use. To iterate again, call the generator function again to get a fresh object.
yield awaits promises for you
Async generators treat yielded promises in a way sync generators do not. In an async generator, yield somePromise waits for the promise and then yields its resolved value. The consumer never receives a promise as value.
async function* fromPromises() {
yield Promise.resolve(1);
yield new Promise((resolve) => setTimeout(() => resolve(2), 50));
yield 3;
}
async function main() {
for await (const v of fromPromises()) {
console.log(v, typeof v); // 1 'number', 2 'number', 3 'number'
}
}
main();So yield await p and yield p behave the same here. Writing the await explicitly is still common because it makes the intent obvious. If the yielded promise rejects, the rejection is thrown at the yield inside the generator, where a try/catch in the body can catch it. The error-handling chapter covers what happens when nothing catches it.
Sync generators versus async generators
| Aspect | `function*` | `async function*` |
|---|---|---|
| `next()` returns | `{ value, done }` directly | A promise of `{ value, done }` |
| Iterable via | `Symbol.iterator` | `Symbol.asyncIterator` |
| Consumed with | `for...of`, spread, destructuring | `for await...of`, `Array.fromAsync` |
| `await` in body | Not allowed | Allowed |
| `yield promise` | Yields the promise object itself | Awaits it and yields the resolved value |
| Spread `[...gen()]` | Works | Throws TypeError (not sync iterable) |
You can write a sync generator that yields promises and loop over it with for await...of. The loop awaits each value, so the output looks the same. The difference is timing. A sync generator produces all its promises up front if something pulls them eagerly, and the work behind them may already be running. An async generator does not start the next step until the consumer asks for it. The later chapter on sync iterables in for await...of looks at this more closely.
A practical producer: paging through results
Async generators work well when you need to hide a multi-step async process behind a simple stream of values. Paging through an API is a typical case. The example below uses a fake fetchPage so you can run it without a network:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Simulated API: each page has some items and a pointer to the next page.
async function fetchPage(page) {
await sleep(50);
const pages = { 1: ['a', 'b'], 2: ['c', 'd'], 3: ['e'] };
console.log(`fetched page ${page}`);
return { items: pages[page] ?? [], next: page < 3 ? page + 1 : null };
}
async function* allItems() {
let page = 1;
while (page !== null) {
const { items, next } = await fetchPage(page);
for (const item of items) {
yield item;
}
page = next;
}
}
async function main() {
for await (const item of allItems()) {
console.log(item);
}
}
main();The output interleaves fetches and items:
fetched page 1
a
b
fetched page 2
c
d
fetched page 3
ePage 2 is not requested until the consumer has taken both items from page 1. If the consumer stops early, the remaining pages are never fetched. The consumer sees a flat sequence of items and knows nothing about pages. A later chapter shows a shorter way to write the inner loop with yield* and builds filter and limit stages on top of this generator.
Calls to next() are queued, not run in parallel
What happens if a consumer calls next() several times without waiting? The generator does not run several copies of its body. It queues the requests and settles them in order, one step of the body at a time.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* slow() {
await sleep(100);
yield 'first';
await sleep(100);
yield 'second';
}
async function main() {
const gen = slow();
const start = Date.now();
const results = await Promise.all([gen.next(), gen.next(), gen.next()]);
console.log(results);
// [ { value: 'first', done: false },
// { value: 'second', done: false },
// { value: undefined, done: true } ]
console.log(`about ${Math.round((Date.now() - start) / 100) * 100} ms`); // about 200 ms
}
main();The total is about 200 ms, not 100 ms. Even with Promise.all, an async generator produces values strictly in sequence. This guarantee is useful because values never arrive out of order. It also means an async generator is the wrong tool on its own when you want concurrency. The chapter on sequential loops versus concurrent work covers what to use instead.
Sending values in with next(value)
As with sync generators, the argument you pass to next(value) becomes the result of the yield expression the body is paused on. The argument to the first next() is ignored, because no yield is waiting yet.
async function* accumulator() {
let total = 0;
while (true) {
const amount = yield total;
total += amount ?? 0;
}
}
async function main() {
const acc = accumulator();
console.log((await acc.next()).value); // 0 (starts the body)
console.log((await acc.next(5)).value); // 5
console.log((await acc.next(10)).value); // 15
}
main();for await...of always calls next() with no argument, so this two-way style only applies when you drive the generator by hand. You will rarely need it for data streams.
Common errors
yieldinside a callback.items.forEach((x) => { yield x; })is a syntax error, becauseyieldbelongs to the innermost function, and the arrow function is not a generator. Use afor...ofloop inside the generator instead.for awaitin a non-async function. A generator that consumes another async source must itself beasync function*. A plainfunction*cannot containawaitorfor await.- Expecting the body to run on call. Side effects at the top of the body, such as logging or opening a connection, happen on the first
next(), not when you call the function. - Reusing an exhausted generator. A second
for await...ofover the same object runs zero times. Call the function again. - Spreading an async generator.
[...gen()]throws because the object has noSymbol.iterator. Collect with afor await...ofloop or withArray.fromAsync, covered in the last chapter. - Infinite generators without a stop. A
while (true)producer is fine as long as the consumer breaks out. The loop must have an exit condition somewhere.
Exercise
What does this program print, and in what order? async function* g() { console.log('A'); yield Promise.resolve('B'); console.log('C'); } async function main() { const it = g(); console.log('D'); const r1 = await it.next(); console.log(r1.value); const r2 = await it.next(); console.log(r2.done); } main();
Show answer
It prints D, A, B, C, true. Calling g() runs none of the body, so D comes first. The first next() runs the body until the yield, which logs A. The yield awaits the promise, so r1.value is the string 'B' and not a promise. The second next() resumes the body, which logs C, and the function then ends, so r2.done is true.
Exercise
Write an async generator ticks(count, ms) that yields the numbers 1 to count, waiting ms milliseconds before each one. Then consume it with for await...of and log each number.
Show answer
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); async function* ticks(count, ms) { for (let i = 1; i <= count; i++) { await sleep(ms); yield i; } } async function main() { for await (const n of ticks(3, 200)) console.log(n); } main(); The waiting happens inside the generator, and each await sleep(ms) runs only after the consumer asks for the next value.
Exercise
A teammate calls Promise.all([gen.next(), gen.next(), gen.next()]) on an async generator whose body awaits a 1-second request before each yield, hoping to finish in about 1 second. How long does it take, and why?
Show answer
It takes about 3 seconds. An async generator queues next() calls and runs its body one step at a time, so the second request does not start until the first value has been yielded. To run the requests at the same time, start the promises yourself (for example with Promise.all over an array of request calls) instead of pulling them through one generator.