JavaScript › Async Iterators & Streams

How do you write an async generator function?

Intermediate

Answer

Combine function* with async: async function*. Each yield can await a value first, and calling the generator returns an async iterable you can consume with for-await-of.
async function* fetchPages(url) {
  let next = url;
  while (next) {
    const res = await fetch(next);
    const data = await res.json();
    yield data.items;
    next = data.nextPage;
  }
}
Real-world example Lazily fetching paginated API results page-by-page, only when the consumer asks for more.

Common follow-ups: How would you stop consuming an async generator early?