← Back to Node.js, page 3

nodejs-0053 · Easy fresher

What are async iterators and async generators, and how do you use them with for await...of?

An async iterable has a [Symbol.asyncIterator]() method that returns an object whose next() returns a promise of { value, done }. An async generator function (async function*) creates one easily. for await...of reads values one at a time, waiting for each, and calls return() on the iterator when you break out early.

Full answer

A normal iterator hands out values one by one, but each value must be ready now. An async iterator hands out promises, so each value can arrive later: a page of an API, a chunk of a file, a message from a queue.

Pieces:

  • Async iterable: an object with Symbol.asyncIterator.
  • Async iterator: an object with next() that returns a promise of { value, done }.
  • Async generator: async function* name() { yield value; }. Node builds the iterator for you. You can await inside it, and yield values.
  • for await (const item of source) runs the loop body for each item, in order, waiting between items.

Why it is useful:

  • Pagination without loading all pages: yield items page by page, and stop fetching when the loop stops.
  • Streams are async iterable: for await (const chunk of readable) handles backpressure for you.
  • Early exit: break, return or throw inside the loop calls the iterator's return() method. In an async generator, that triggers finally blocks, so cleanup (closing a cursor or connection) runs.
  • Pipeline stages: async generator functions can be used in stream.pipeline and as transformations.

Notes: items are processed one after another, so a for await loop is sequential. For parallel work, collect promises or use a concurrency limit. Errors thrown by the source reject the loop, so wrap the loop in try/catch.

javascript
// A fake paginated API: 3 pages with 2 students each.
const pages = [['Asha', 'Ravi'], ['Meera', 'Kabir'], ['Zoya', 'Dev']];
const fetchPage = async (n) => {
  await new Promise((r) => setTimeout(r, 5));
  return { items: pages[n] || [], hasMore: n < pages.length - 1 };
};

// An async generator hides pagination from the caller.
async function* allStudents() {
  let page = 0;
  try {
    while (true) {
      const { items, hasMore } = await fetchPage(page++);
      yield* items; // yields one student at a time
      if (!hasMore) return;
    }
  } finally {
    console.log('cleanup: the generator was closed after page', page);
  }
}

// A hand-written async iterable.
const countdown = {
  from: 3,
  [Symbol.asyncIterator]() {
    let n = this.from;
    return {
      async next() {
        await new Promise((r) => setTimeout(r, 1));
        return n > 0 ? { value: n--, done: false } : { value: undefined, done: true };
      },
    };
  },
};

async function main() {
  const all = [];
  for await (const name of allStudents()) all.push(name);
  console.log('all students:', all.join(', '));

  // Stop early: the finally block still runs.
  for await (const name of allStudents()) {
    console.log('first student only:', name);
    break;
  }

  const numbers = [];
  for await (const n of countdown) numbers.push(n);
  console.log('countdown:', numbers.join(' '));
}

main();

After break, the generator's finally block prints the page counter, which shows that early exit triggers cleanup. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): cleanup: the generator was closed after page 3 all students: Asha, Ravi, Meera, Kabir, Zoya, Dev first student only: Asha cleanup: the generator was closed after page 1 countdown: 3 2 1

Key points

  • Async iterables yield promises of values over time.
  • async function* is the easy way to write one.
  • for await is sequential and applies backpressure.
  • break calls return(), which runs finally blocks.

Common mistakes

  • Using for await on something that is not async iterable and not an array of promises.
  • Expecting for await to run items in parallel.
  • Forgetting try/finally for resources inside generators.
  • Mixing await in for...of on an array of promises, which does not wait for them in order of completion.

Follow-ups

  • How do you turn an event emitter into an async iterator?
  • What does yield* do in an async generator?
  • How would you process the pages in parallel while keeping the order?

Tips

  • Contrast with a callback: the consumer pulls the data.
  • Show the finally block on early exit.
  • Mention that readable streams are async iterable.