Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 133 ยท Asynchronous Programming

Async Iterators and Generators

Learn async iterators in Node.js - for await...of, async generators, Symbol.asyncIterator, early exit and cleanup, events.on, readline lines and a paginated iterator.

A promise gives you one future value. But a lot of things in Node.js produce many values over time: lines of a file, chunks of a download, events from a server, pages of an API. For years the choices were awkward: callbacks fired many times, or event listeners you had to wire up and tear down by hand. Async iterators give such sources the same shape as an ordinary loop: you write for await (const item of source) and each item arrives when it is ready.

This lesson builds the idea from the ground up. First the plain iterator protocol, then the async version, then async generators (the easy way to make one), and finally the places where Node already hands you async iterators: streams, readline and events.on. If you are still shaky on await itself, read async/await Patterns first.

A quick reminder: sync iterators

An iterable is any object with a [Symbol.iterator]() method that returns an iterator: an object with a next() method returning { value, done }. for...of, spread and destructuring all use that protocol. A generator function (function*) is the shortcut for writing one.

NODE
function* countUp(limit) {
  for (let i = 1; i <= limit; i++) {
    yield i;
  }
}

The limitation is that next() must return its result immediately. If the next value needs a network call or a timer, a synchronous iterator cannot wait for it. That is exactly the gap async iterators fill.

for await...of

for await...of loops over an async iterable. On each turn it calls next(), which returns a promise of { value, done }, waits for it, and runs the loop body with the value. It also works on ordinary iterables, awaiting each item, which is handy for an array of promises.

Node.js for await over an array of promises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The loop is strictly sequential: the body for item 1 finishes before the loop asks for item 2. That makes it simple to reason about, and it is also why a for await is the wrong tool when you want items processed in parallel (see Concurrency Control and Queues). Like await, for await is only allowed inside an async function or at the top level of an ES module.

Async generators

An async generator is declared with async function*. It can use both await and yield, and calling it gives you an object that is an async iterator and async iterable at the same time. Each yield produces one value for the consumer; the generator pauses there until the consumer asks for the next one.

Node.js An async generator that ticks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Watch the interleaving in the output. The generator body does not run ahead on its own: it produces a value, suspends, and only continues when the loop comes back for more. That demand-driven behaviour is called pull-based flow, and it is the reason async generators handle huge or endless sources with constant memory. Nothing is produced that nobody asked for.

A generator that is never consumed never runs at all. ticker(3) by itself does nothing until something calls next() on it.

Early exit and cleanup

What happens if the consumer stops early with break, return or a throw? The loop calls the iterator's return() method, which resumes the generator at its current yield as if there were a return statement there. Any finally block in the generator then runs. This is how async generators release resources: close the file, free the connection, clear the timer.

Node.js break triggers the generator's finally block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The finally output appears before "after the loop" because the loop waits for the generator to finish its cleanup. Remember this when you write your own sources: put the cleanup in finally, never in code after the last yield, because that code is skipped when the consumer leaves early.

An error thrown inside the generator is delivered to the consumer as a rejected next() promise, so try/catch around the for await catches it, exactly like a rejected await.

Writing the protocol by hand: Symbol.asyncIterator

An async generator covers most needs. Sometimes you want a class whose instances can be looped over; then you add a method named [Symbol.asyncIterator](). It must return an object with a next() method that returns a promise, and optionally a return() method for cleanup. The easiest implementation of that method is itself an async generator.

Node.js A class with Symbol.asyncIterator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You can also write the raw protocol, which shows what for await really does. This version returns the iterator object itself:

NODE
const manual = {
  [Symbol.asyncIterator]() {
    let i = 0;
    return {
      async next() {
        i += 1;
        return i <= 2 ? { value: i, done: false } : { value: undefined, done: true };
      },
      async return() {
        // called when the consumer breaks out early
        return { value: undefined, done: true };
      },
    };
  },
};

Prefer the generator form. It handles return(), throw(), queuing of overlapping calls and cleanup for you.

What happens when you pass the wrong thing

for await needs Symbol.asyncIterator (or, as a fallback, Symbol.iterator). A plain object has neither, and the error tells you so.

Node.js Looping over a plain object (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

You will see TypeError: config is not async iterable, with the stack trace pointing at main.mjs. The fix is to loop over something that is iterable, for example Object.entries(config).

Async iterators already in Node

You rarely write the protocol yourself, because much of Node's standard library already speaks it.

Readable streams

Every Readable stream is an async iterable of its chunks, which is usually the cleanest way to consume a stream. Errors become exceptions and the stream is destroyed if you break out early. See Streams Fundamentals for the full story.

readline: lines as an async iterator

readline.createInterface turns any readable (a file, a socket, standard input) into an async iterable of lines. That is the idiomatic way to process a file line by line without loading it all.

Node.js Reading lines with readline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The empty line is delivered as "". In real programs you would replace Readable.from(...) with fs.createReadStream(path) or process.stdin.

events.on: events as an async iterator

EventEmitter listeners are push-based callbacks. events.on(emitter, 'name') converts them into an async iterator that yields the argument arrays of every emit. Pass an AbortSignal to stop it, because otherwise the loop waits forever for the next event.

Node.js Turning events into a for await loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Events emitted while your loop body is busy are buffered and delivered afterwards, so none are lost between iterations. The loop ends by throwing an AbortError when the signal fires, which is why the for await sits in a try/catch. More on that in AbortController and Cancellation.

Building a paginated iterator

APIs return big lists in pages. An async generator hides the paging completely: callers see one flat stream of items and fetch pages only as fast as they consume them. Here the "API" is a fake in-memory function so the example is repeatable; against a real service you would swap in fetch (see HTTP Clients).

Node.js One flat stream out of three pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two details matter. yield* delegates to another iterable, passing its items through one by one. And because the pages are pulled lazily, breaking after Dara means page three is never fetched: you saved a request just by stopping the loop.

Pitfalls and design notes

  • Forgetting await in for await. A plain for...of over an async generator throws a TypeError, because the generator has no Symbol.iterator.
  • Sequential by default. Items are processed one at a time. To run work in parallel, collect promises with a concurrency limit or use a queue.
  • Always pair infinite sources with a way out. events.on, a ticking generator or a socket never ends by itself: use break, an AbortSignal or a timeout.
  • Cleanup belongs in finally. Early exits skip the code after the last yield.
  • Do not mix a long loop body with a fast producer without thinking about memory. Pull-based generators and streams apply backpressure automatically, but events.on buffers every event while you are busy.
  • Errors surface at the loop. Wrap the for await in try/catch, not the generator call.
  • Use Array.fromAsync (Node 22+) when you really do want all items in an array: const all = await Array.fromAsync(listUsers()).

Use async iterators for sequences that arrive over time and that you want to consume with ordinary control flow. Use a promise for a single result, and an EventEmitter listener when many independent consumers need push notifications.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the loop body of for await...of wait for before running?

    Each turn calls next(), which returns a promise of { value, done }. The body runs once that promise resolves.
  2. 2. A consumer breaks out of a for await loop over an async generator. When does the generator's finally block run?

    Leaving the loop early calls return(), which resumes the generator as if there were a return at its current yield, so finally blocks run.
  3. 3. What happens if you call an async generator function but never iterate the result?

    Generators are lazy. The body only starts running when something calls next().
  4. 4. What does events.on(emitter, 'x') yield on each turn of the loop?

    The iterator yields the argument list of each emit as an array, which is why the examples destructure with [text, id].
  5. 5. Which statement about for await...of is true?

    The loop waits for each item before asking for the next one, so processing is sequential. It works on any async or sync iterable and supports break.

Summary

  • An async iterator has a next() method returning a promise of { value, done }; an async iterable exposes it through [Symbol.asyncIterator]().
  • for await...of consumes one, sequentially, and is allowed in async functions and top-level module code.
  • async function* is the easy way to write one: await to wait, yield to produce, pulled on demand.
  • Leaving a loop early calls return(), so put cleanup in finally.
  • Node gives you async iterators for streams, readline lines and events.on; use an AbortSignal to end endless ones.
  • Wrap paging, polling and other awkward sources in an async generator so callers see a simple flat loop.

Next: AsyncLocalStorage and Context