← Back to JavaScript, page 7

javascript-0140 · Hard senior

What are async generators and for await...of, and when would you use them, for example for pagination or streaming data?

An async generator (async function*) produces a sequence of values over time, awaiting between them, and for await...of consumes it one value at a time. It suits paginated APIs, streams, and event sources because values are produced lazily, backpressure is natural (the next item is requested only after the loop body finishes), and breaking out of the loop runs the generator's cleanup code in finally blocks.

Full answer

A normal generator yields values synchronously. An async generator is declared with async function*, can use await inside, and its yield produces a promise-wrapped value. It returns an object with Symbol.asyncIterator, and each next() call returns a promise of { value, done }. You consume it with for await (const item of source), which also accepts sync iterables of promises, and works in an async function or at module top level.

Why use it:

  • Pagination: write the loop that fetches page after page inside the generator and yield each item. The caller sees a flat sequence and does not know about pages. The next page is fetched only when the consumer asks for more.
  • Backpressure: the generator pauses at yield until the consumer calls next() again. A slow consumer slows the producer, so there is no unbounded buffer, unlike an event emitter.
  • Streams: Node.js readable streams, the readline interface, and the fetch response body (for await (const chunk of response.body) works in Node.js and in some browsers) are async iterable.
  • Cleanup: if the consumer leaves the loop early with break, return, or by throwing, the engine calls the generator's return() method, which runs its finally blocks. Close connections or file handles in finally.
  • Composition: write small async generator functions, such as map, filter, and take, and chain them, like lazy pipelines.

Details: the generator runs one next() at a time (requests are queued), errors thrown in the generator reject the pending next() promise and end the loop, and an await inside for await loops is sequential. For parallel work use Promise.all with batches instead.

To make your own class async iterable, define [Symbol.asyncIterator]() { return { next() {...} } }, or simply write async *[Symbol.asyncIterator]().

An async generator that never finishes, such as one that polls a feed, needs an exit condition or an AbortSignal, otherwise the loop runs forever.

javascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const log = [];

// a fake paginated API
const database = Array.from({ length: 7 }, (_, i) => `item-${i + 1}`);
async function fetchPage(page, size) {
  await sleep(1);
  log.push(`fetching page ${page}`);
  const items = database.slice((page - 1) * size, page * size);
  return { items, hasMore: page * size < database.length };
}

async function* paginate(size) {
  let page = 1;
  try {
    while (true) {
      const { items, hasMore } = await fetchPage(page++, size);
      yield* items;
      if (!hasMore) return;
    }
  } finally {
    log.push('paginate cleanup ran');
  }
}

async function* take(source, count) {
  if (count <= 0) return;
  let taken = 0;
  for await (const item of source) {
    yield item;
    if (++taken >= count) return;
  }
}

async function* map(source, fn) {
  for await (const item of source) yield fn(item);
}

class Countdown {
  constructor(from) {
    this.from = from;
  }
  async *[Symbol.asyncIterator]() {
    for (let n = this.from; n > 0; n--) {
      await sleep(1);
      yield n;
    }
  }
}

async function main() {
  const all = [];
  for await (const item of paginate(3)) all.push(item);
  console.log(all.length, 'items,', log.filter((line) => line.startsWith('fetching')).length, 'pages fetched');

  log.length = 0;
  for await (const item of paginate(3)) {
    if (item === 'item-2') break; // leaving early runs the finally block
  }
  console.log(log);

  log.length = 0;
  const firstFour = [];
  for await (const item of map(take(paginate(2), 4), (text) => text.toUpperCase())) firstFour.push(item);
  console.log(firstFour, log);

  const countdown = [];
  for await (const n of new Countdown(3)) countdown.push(n);
  console.log(countdown);

  for await (const value of [Promise.resolve('a'), 'b', sleep(1).then(() => 'c')]) process.stdout.write(value + ' ');
  console.log('(for await over an array of promises)');

  async function* failing() {
    yield 1;
    throw new Error('source failed');
  }
  try {
    for await (const value of failing()) console.log('got', value);
  } catch (error) {
    console.log('caught:', error.message);
  }
}
main();

Run with Node.js v24.22.1 as js-140.js; two runs gave identical output. Output: 7 items, 3 pages fetched [ 'fetching page 1', 'paginate cleanup ran' ] [ 'ITEM-1', 'ITEM-2', 'ITEM-3', 'ITEM-4' ] [ 'fetching page 1', 'fetching page 2', 'paginate cleanup ran' ] [ 3, 2, 1 ] a b c (for await over an array of promises) got 1 caught: source failed

Key points

  • async function* yields values over time; for await consumes them one at a time.
  • Great for pagination, streams, and event sources, hiding the pages from the caller.
  • Natural backpressure: the producer waits until the consumer asks for the next value.
  • Leaving the loop early calls return(), so finally blocks clean up resources.
  • Own classes can define Symbol.asyncIterator; add an abort signal for endless sources.

Common mistakes

  • Using forEach or map with await and expecting sequential asynchronous iteration.
  • Forgetting cleanup in finally, so connections stay open when the consumer stops early.
  • Writing an endless polling generator with no way to stop it.
  • Awaiting independent items one by one when parallel work would be faster.

Follow-ups

  • What happens to queued next() calls on an async generator?
  • How do Node.js readable streams use async iteration, and what are the backpressure implications?
  • How would you add cancellation with AbortSignal to an async generator?

Tips

  • Explain pagination as the motivating example.
  • Mention backpressure and finally-based cleanup.
  • Show that for await also accepts async iterables you build with Symbol.asyncIterator.