Node.js
Async generators
Learn async generator functions.
Streaming data with async generators
An async generator can produce values that resolve promises with yield await. This is used to stream data piece by piece. Example: async function* fetchItems(items) { for (const item of items) { yield await Promise.resolve(item * 2); } }.
This generator doubles each item of an array and yields them one by one. The power of the yield await pattern: yield gives a promise, await resolves it, for await takes the resolved value. This is useful in scenarios where each item is a database query or an API call. Calling fetchItems([1, 2, 3]) streams the values 2, 4, 6. All items are produced on demand, not at once; this gives memory efficiency.
Consuming an async generator with for await
You consume an async generator with for await...of. Each loop step advances the generator to the next yield and gives the value. Example: for await (const v of fetchItems([1, 2, 3])) { console.log(v); }.
This loop continues until the generator is done. Each yield await is a pause: for await waits for the promise to resolve, takes the value and runs the loop body. This is like a normal for...of loop, but each step has an await. The output: 2, 4, 6. This pattern is ideal for processing large datasets without loading them all into memory; each item is produced only when needed.
Exercise Write an async generator that doubles
Define async function* fetchItems(items) with for (const item of items) { yield await Promise.resolve(item * 2); }. Inside async function main() write for await (const v of fetchItems([1, 2, 3])) { console.log("Value: " + v); }. Call main().
Show example solution
async function* fetchItems(items) {
for (const item of items) {
yield await Promise.resolve(item * 2);
}
}
async function main() {
for await (const v of fetchItems([1, 2, 3])) {
console.log("Value: " + v);
}
}
main();
Test yourself
-
Complete the yield await line
yield ____ Promise.resolve(item * 2);
Show answer
yield await Promise.resolve(item * 2);
-
Match each piece to its role
- async function*
- Defines a generator
- yield await
- Resolves a promise and yields
- for await
- Consumes a generator
- Promise.resolve
- Creates a promise
-
What does async function* return?
const gen = fetchItems([1, 2, 3]);
- A number
- Bir dizi
- Bir promise
- Bir async iterator
Show answer
Bir async iterator — async function* returns an async iterator when called.
Next lesson: Concurrency limit