CodeBlanks Logo Icon CodeBlanks

Async iteration

Learn async iteration with for await...of.

Async iteration: for await...of

Async iteration is the way to consume an async source in order. The for await...of loop advances by awaiting each item. It is the async version of for...of.

The easiest way to produce an async iterator is an async generator: async function* numbers() { yield 1; yield 2; yield 3; }. This function returns an async iterator. With for await (const n of numbers()) { console.log(n); } you get each value by awaiting. The output: 1, 2, 3. An async generator's yield can return a promise; for await resolves it and gives the value. This is ideal for streaming data piece by piece.

Defining an async generator

An async generator is defined with async function*. It produces values with yield. Each yield is a pause: the generator waits until the consumer asks for the next value.

Example: async function* numbers() { yield 1; yield 2; yield 3; }. When called, this function returns an async iterator. With for await (const n of numbers()) you get each value from yield. The power of async generators is that yield can return a promise: yield await fetch(url). for await resolves this promise. This is the basic tool for consuming streaming sources like database pagination or file lines.

Practice Write an async generator and for await

Define async function* numbers() with yield 1; yield 2; yield 3;. Inside async function main() write for await (const n of numbers()) { console.log("Number: " + n); }. Call main().

Starter code

index.js
// Produce numbers with an async generator, consume in a loop
// write here

Sample solution

index.js
async function* numbers() {
  yield 1;
  yield 2;
  yield 3;
}

async function main() {
  for await (const n of numbers()) {
    console.log("Number: " + n);
  }
}

main();

Expected output

Sayı: 1
Sayı: 2
Sayı: 3

Questions and answers

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

1 What does for await...of do?

index.js
for await (const n of numbers()) { console.log(n); }
  • Diziyi senkron gezer
  • Creates a Promise
  • Iterates over each item, awaiting it Correct answer
  • Skips the loop

Explanation: for await advances by awaiting each item.

2 Complete the for await line

Question
for ____ (const n of numbers()) { console.log(n); }
Answer
for await (const n of numbers()) { console.log(n); }

Explanation: for await consumes an async iterator.

3 Match each piece to its role

Term Meaning
async function* Defines an async generator
yield Produces a value
for await Consumes an async iterator
numbers() Returns an iterator

All lessons in Intermediate