Async generators
Learn async generators with async function* and iterate them with for await...of.
Async generators
With async function* you define an async generator. This generator can yield Promises and use await in its body. Each yield can wait for a Promise to resolve.
async function* stream() {
yield await fetch('/data');
yield await fetch('/more');
}Async generators are ideal for producing values from network requests or database queries step by step.
The for await...of loop
To iterate an async generator, use the for await...of loop. This loop awaits each value as a Promise and delivers them in order. You cannot use for...of because values arrive over time.
for await (const chunk of stream()) {
console.log(chunk);
}The loop body runs for each chunk; when the generator finishes, the loop ends.
Exercise Write an async generator
Write an async generator named fetchNumbers with yield await Promise.resolve(1), yield await Promise.resolve(2), yield await Promise.resolve(3). Iterate the generator with for await...of and log each value with console.log.
Show example solution
async function* fetchNumbers() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
for await (const n of fetchNumbers()) {
console.log(n);
}
Test yourself
-
Which loop is used to iterate an async generator?
- for await...of
- for...in
- forEach
- while...await
Show answer
for await...of — Correct! for await...of awaits each value from an async generator in order.
-
Complete the for await loop
async function* stream() { yield 1; } ____ (const value of stream()) { console.log(value); }Show answer
async function* stream() { yield 1; } for await (const value of stream()) { console.log(value); } -
Match the async generator terms
- async function*
- defines async generator
- for await...of
- iterates async generator
- await
- waits for Promise