Sub topic 4
Producing Async Sequences with async function*
This chapter assumes you know Promises and async/await, the async iteration protocol from the previous chapter (a next() that returns a Promise of { value, done }), and how for await...of consumes an async iterable. Here you will write the producer side using async generator functions.
The syntax
An async generator function combines two features. It is declared with async function*, so it can use both await and yield in its body:
awaitpauses the generator until a Promise settles.yieldhands one value to the consumer and pauses 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();You don't write Symbol.asyncIterator or next() anywhere. The engine builds the protocol for you.
What calling it returns
Calling countdown(3) does not run any of its body. It returns an async generator object right away. That object is:
- an async iterator, because it has
next(),return(), andthrow(), each returning a Promise; - an async iterable, because its
[Symbol.asyncIterator]()method returns the object itself.
This is why you can pass a generator call straight to for await...of. The body starts running on the first next() call and stops at each yield.
async function* numbers() {
console.log('started');
yield 1;
yield Promise.resolve(2); // awaited before it is delivered
return 3;
}
async function main() {
const gen = numbers();
console.log('created');
console.log(gen[Symbol.asyncIterator]() === gen); // true
console.log(await gen.next()); // started, then { value: 1, done: false }
console.log(await gen.next()); // { value: 2, done: false }
console.log(await gen.next()); // { value: 3, done: true }
console.log(await gen.next()); // { value: undefined, done: true }
}
main();The output starts with created and true, and only then started. The body is lazy.
How values flow
Behaviors worth knowing
| Behavior | What happens |
|---|---|
| `yield somePromise` | The Promise is awaited first, and the consumer receives the settled value, never a Promise. |
| `return value` | Produces `{ value, done: true }`. `for await...of` ignores this value. |
| Calling `next()` several times without awaiting | Requests are queued and resolved in order, one per `yield`. |
| No `yield` reached yet | The Promise from `next()` stays pending until the generator reaches its next `yield` or finishes. |
Generators as methods
Method syntax lets you make any object async iterable with very little code:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const feed = {
messages: ['hello', 'world'],
async *[Symbol.asyncIterator]() {
for (const m of this.messages) {
await sleep(50);
yield m;
}
}
};
async function main() {
for await (const m of feed) {
console.log(m); // hello, world
}
}
main();Each for await...of over feed calls the method again and gets a fresh generator, so the object can be looped over more than once. A generator object can be consumed only once: after it finishes, it stays done.
Exercise
Write an async generator delayedEcho(words, ms) that waits ms milliseconds before yielding each word in words. What does await delayedEcho(['a'], 10).next() resolve to, and what does a second next() call on the same generator resolve to?
Show answer
async function* delayedEcho(words, ms) { for (const w of words) { await new Promise((r) => setTimeout(r, ms)); yield w; } }. The first next() resolves to { value: 'a', done: false } after about 10 ms. A second next() on the same generator resolves to { value: undefined, done: true }.
Exercise
In the numbers() example, why is 'created' logged before 'started'?
Show answer
Calling an async generator function only creates the generator object. None of the body runs until the first next() call, and the first next() happens after 'created' is logged.