What is async generator?

An async generator (async function*) is a generator that can await inside its body and yields values asynchronously; you consume it with for await...of, which makes it ideal for streams of data that arrive over time.

How it works

  • next() returns a promise of { value, done }.
  • Inside, you can await (fetch a page, wait for a message) and yield results one by one.
  • Consumers use for await (const item of asyncGen()) { ... }, which waits for each value in turn.
  • It implements Symbol.asyncIterator.

Use cases

  • Paginated APIs: yield items page by page and fetch the next page only when the consumer needs more.
  • Streams: reading a fetch response body chunk by chunk, Node streams (which are async iterable), file reading, log tailing.
  • Event sources: turning WebSocket messages or DOM events into an async sequence.
  • Rate-limited processing: process items as they arrive without loading everything into memory.
  • Streaming AI responses token by token.

Benefits

  • Backpressure for free: the producer pauses at each yield until the consumer asks for the next item.
  • Clean early exit: break in for await calls return(), which runs the generator's finally (close connections, abort requests).

Related

Array.fromAsync(asyncIterable) collects everything into an array. ReadableStream is also async iterable in modern runtimes.

Code example

js
1// Fake paginated API
2const DB = Array.from({ length: 23 }, (_, i) => ({ id: i + 1, name: `item ${i + 1}` }));
3async function fetchPage(page, size = 10) {
4 await new Promise((r) => setTimeout(r, 10)); // network delay
5 const items = DB.slice((page - 1) * size, page * size);
6 return { items, hasMore: page * size < DB.length };
7}
8
9// Async generator: yields items, fetching pages only as needed
10async function* allItems() {
11 let page = 1;
12 let pagesFetched = 0;
13 try {
14 while (true) {
15 const { items, hasMore } = await fetchPage(page++);
16 pagesFetched++;
17 yield* items;
18 if (!hasMore) return;
19 }
20 } finally {
21 console.log(`pages fetched: ${pagesFetched}`); // runs on completion OR early break
22 }
23}
24
25// Consume lazily: stop as soon as we find what we need
26for await (const item of allItems()) {
27 if (item.id === 12) {
28 console.log("found", item.name); // found item 12
29 break; // only 2 of the 3 pages are fetched
30 }
31}
32
33// Collect everything
34const everything = await Array.fromAsync(allItems());
35console.log(everything.length); // 23
36
37// Streaming text in chunks (e.g. an AI response)
38async function* streamWords(text) {
39 for (const word of text.split(" ")) {
40 await new Promise((r) => setTimeout(r, 5));
41 yield word;
42 }
43}
44let output = "";
45for await (const w of streamWords("tokens arrive one at a time")) output += w + " ";
46console.log(output.trim());

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app