Skip to content
jshacks.dev
Async

Async Iterators and the for await...of Loop

Learn how async iterators and for await of work in JavaScript, how to write an async generator and how to consume paged APIs, streams and events as sequences.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Redis and Apache Kafka logos.

An array gives you all its values at once. A promise gives you one value later. An async iterator gives you many values, each one later, and it fits any source that produces data over time: pages of an API, lines of a file, chunks from a network stream, messages from a queue. The consumer is a for await...of loop that waits for each value in turn, with the same break, continue and try/catch you already use. The producer is usually an async generator, a function declared async function* that yields values and can await in between. This post explains the protocol on Node.js 24 with printed output, writes a few async generators, shows the most common real uses and covers cancellation, error handling and the helper methods that now exist for working with sequences.

The protocol

A synchronous iterable has a Symbol.iterator method that returns an object with next(), and each call returns { value, done }. An async iterable has Symbol.asyncIterator, and its next() returns a promise of that object. That is the whole difference.

JavaScript
const countdown = {
  [Symbol.asyncIterator]() {
    let n = 3;

    return {
      async next() {
        await new Promise((resolve) => setTimeout(resolve, 10));
        return n > 0 ? { value: n--, done: false } : { value: undefined, done: true };
      },
    };
  },
};

for await (const value of countdown) {
  console.log(value);
}
Text
3
2
1

The loop calls next(), waits for the promise, and stops when done is true. Each step can take as long as it needs, and the loop body runs between steps. Writing the object by hand is rare. An async generator does the same job with less code.

Async generators

async function* combines await and yield. The function pauses at each yield, and the loop's next iteration resumes it.

JavaScript
async function* ticker(count, ms) {
  for (let i = 1; i <= count; i++) {
    await new Promise((resolve) => setTimeout(resolve, ms));
    yield i;
  }
}

for await (const tick of ticker(3, 10)) {
  console.log("tick", tick);
}
Text
tick 1
tick 2
tick 3

The generator does not run ahead. It runs only when the consumer asks for the next value, so a slow consumer slows the producer, which is a natural form of backpressure. A generator that fetches pages of an API will not request page three until the loop body has finished with page two.

Paged APIs

The most common real use is hiding pagination behind a single loop.

JavaScript
const pages = {
  1: { items: ["a", "b"], next: 2 },
  2: { items: ["c", "d"], next: 3 },
  3: { items: ["e"], next: null },
};

async function fetchPage(number) {
  await new Promise((resolve) => setTimeout(resolve, 5));
  return pages[number];
}

async function* allItems() {
  let page = 1;

  while (page !== null) {
    const result = await fetchPage(page);
    yield* result.items;
    page = result.next;
  }
}

for await (const item of allItems()) {
  console.log(item);
}
Text
a
b
c
d
e

yield* inside an async generator delegates to an iterable, so every item of the page comes out one at a time. The caller never sees pages, and can break out after the third item, and no further page is fetched. That early exit is the main advantage over a function that returns an array of everything.

Early exit and cleanup

When a loop exits early, through break, return or a thrown error, the runtime calls the iterator's return() method. In an async generator, that resumes the generator at the yield as if a return statement was there, so finally blocks run.

JavaScript
async function* withCleanup() {
  try {
    yield 1;
    yield 2;
    yield 3;
  } finally {
    console.log("cleanup ran");
  }
}

for await (const value of withCleanup()) {
  console.log("got", value);
  if (value === 2) break;
}

console.log("loop finished");
Text
got 1
got 2
cleanup ran
loop finished

This is how a generator that holds a file handle, a database cursor or a socket releases it, and it is why resource handling belongs in try/finally inside the generator and not in the caller.

Errors

An error thrown inside the generator, or a rejection from an awaited call, surfaces in the loop as a thrown error, so a surrounding try/catch works.

JavaScript
async function* flaky() {
  yield "ok";
  throw new Error("source failed");
}

try {
  for await (const value of flaky()) {
    console.log(value);
  }
} catch (error) {
  console.log("caught:", error.message);
}
Text
ok
caught: source failed

for await over a sync iterable

for await accepts ordinary iterables too, and awaits each value, so it works as a way to process an array of promises in order.

JavaScript
const promises = [
  new Promise((resolve) => setTimeout(() => resolve("slow"), 30)),
  Promise.resolve("fast"),
];

for await (const value of promises) {
  console.log(value);
}
Text
slow
fast

The results come in array order, not completion order, since the loop waits for the first before looking at the second. This is different from Promise.all, which waits for all of them together, and from a loop of awaits, which is the same behavior written longer. One difference is that a rejected promise later in the array which nobody has handled yet can trigger an unhandled rejection warning while the loop waits on an earlier one.

Where you meet async iterables

Node.js streams. Every readable stream is an async iterable, so reading a file line by line is short.

JavaScript
import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";

const lines = createInterface({ input: createReadStream("notes.txt") });

for await (const line of lines) {
  console.log("line:", line);
}
Text
line: first note
line: second note

This assumes notes.txt contains those two lines. The readline interface handles buffering and line splitting, and the loop sees one string at a time without loading the file.

Web streams. A ReadableStream is async iterable in Node.js and in current browsers, with for await (const chunk of response.body).

Events. events.on(emitter, "name") returns an async iterator of events, so a sequence of messages becomes a loop.

Timers. setInterval from node:timers/promises is an async iterator that yields on every tick.

JavaScript
import { setInterval as every } from "node:timers/promises";

let n = 0;

for await (const _ of every(10)) {
  n += 1;
  if (n === 3) break;
}

console.log("ticks seen:", n);
Text
ticks seen: 3

Iterator helpers and Array.fromAsync

Array.fromAsync collects an async iterable into an array, which is available in Node.js 22 and later and in current browsers.

JavaScript
async function* numbers() {
  yield 1;
  yield 2;
  yield 3;
}

const all = await Array.fromAsync(numbers());
console.log(all);
Text
[ 1, 2, 3 ]

Async iterator helpers, such as map, filter and take directly on async iterators, are a separate proposal that has not reached the standard, so for now write them as small async generators.

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

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

console.log(await Array.fromAsync(take(map(numbers(), (n) => n * 10), 2)));
Text
[ 10, 20 ]

The generators compose by wrapping, and the early return in take triggers cleanup in the source above it.

Concurrency: the loop is sequential

A for await loop handles one value at a time. If each item needs a slow call, the loop does not overlap them. To process several at once, collect a batch and use Promise.all, or use a concurrency helper from a library.

JavaScript
async function* batches(source, size) {
  let batch = [];

  for await (const value of source) {
    batch.push(value);
    if (batch.length === size) {
      yield batch;
      batch = [];
    }
  }

  if (batch.length > 0) yield batch;
}

for await (const batch of batches(numbers(), 2)) {
  console.log(await Promise.all(batch.map(async (n) => n * 2)));
}
Text
[ 2, 4 ]
[ 6 ]

Choosing between an async generator and an event emitter

Both can deliver a sequence of values over time, and the difference is who is in control. An event emitter pushes: the source decides when to emit, and listeners must keep up or buffer. An async generator is pull-based: the consumer asks for the next value, and the source waits to be asked. That makes generators the better choice when the consumer may be slower than the source, when early exit must release resources and when the sequence has a clear end. Emitters are better when there are many independent listeners, when events can arrive at any time and nobody is obliged to read them all.

If you must bridge the two, events.on(emitter, "name") turns an emitter into an async iterator, and it queues events that arrive while your loop body is busy. That queue is unbounded, so for a very chatty source, add your own limit, or drop old values you no longer need.

A last practical point is testing. An async generator is easy to test, since you can drive it with a loop and assert on the values, or collect them with Array.fromAsync, and you can pass a fake source into the functions that consume it. That testability is a good reason to model new sequence-producing code as generators from the start.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.