CodeBlanks Logo Icon CodeBlanks

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.

Practice 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().

Starter code

index.js
// Yield double of each item with an async generator
// Consume in a loop and print
// write here

Sample solution

index.js
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();

Expected output

Değer: 2
Değer: 4
Değer: 6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the yield await line

Question
yield ____ Promise.resolve(item * 2);
Answer
yield await Promise.resolve(item * 2);

Explanation: yield await resolves the promise and yields the value.

2 Match each piece to its role

Term Meaning
async function* Defines a generator
yield await Resolves a promise and yields
for await Consumes a generator
Promise.resolve Creates a promise

3 What does async function* return?

index.js
const gen = fetchItems([1, 2, 3]);
  • A number
  • Bir dizi
  • Bir promise
  • Bir async iterator Correct answer

Explanation: async function* returns an async iterator when called.

All lessons in Intermediate