Codectionary / Developer documentation / JavaScript

Async Generators & for await...of

Async generators combine generators and async functions, defined with async function*, yielding values that may themselves be promises. for await...of consumes an async iterable, automatically awaiting each yielded value - useful for processing streamed data or paginated API results one chunk at a time.

Syntax

async function* name() {
  yield await value;
}
for await (const val of asyncIterable) { }

Examples

Basic Async Generator

Yielding values that resolve asynchronously, one at a time.

async function* fetchPages(baseUrl, totalPages) {
  for (let page = 1; page <= totalPages; page++) {
    const response = await fetch(`${baseUrl}?page=${page}`);
    const data = await response.json();
    yield data;
  }
}

async function processAllPages() {
  for await (const pageData of fetchPages("/api/items", 3)) {
    console.log("Received page:", pageData);
  }
}

Simulating a Delayed Stream

A simplified example showing values arriving over time.

async function* countWithDelay(max) {
  for (let i = 1; i <= max; i++) {
    await new Promise(resolve => setTimeout(resolve, 500));
    yield i;
  }
}

async function run() {
  for await (const num of countWithDelay(3)) {
    console.log(num); // 1, 2, 3 - each one arriving 500ms apart
  }
}
run();

Best practices

  • Use async generators for processing data that naturally arrives in chunks over time, like paginated APIs or streaming responses
  • Use for await...of instead of manually calling .next() and awaiting each result - it handles the iteration protocol for you
  • Remember an async generator function always returns an async iterable, regardless of what individual yields resolve to
  • Combine with try/catch inside the for await...of loop to handle errors from individual chunks without stopping the entire stream

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading