Articles

JavaScript Async Iterators and for await...of Explained

Async iterators let JavaScript loop over data that arrives over time — paginated APIs, streams, events — with for await...of and async generators.

Takina Takina · · 5 min read
JavaScript code in a dark-themed code editor

An async iterator is a JavaScript object that produces a sequence of values one at a time, where each value arrives as a promise. You consume one with a for await...of loop, which waits for each value before running the loop body. Together with async generator functions, they give you a clean, readable way to process data that shows up over time: paginated API results, file chunks, network streams, or events.

From iterators to async iterators

Async iterators are a direct extension of the synchronous iteration protocol. If you know how generators and iterators work, most of this will feel familiar.

A synchronous iterable has a [Symbol.iterator]() method that returns an iterator. Calling next() on that iterator returns { value, done } immediately.

An async iterable has a [Symbol.asyncIterator]() method instead. Its iterator’s next() returns a promise that resolves to { value, done }. That single difference — a promise around each result — lets the producer take as long as it needs to supply the next item.

Sync iteratorAsync iterator
Protocol method[Symbol.iterator]()[Symbol.asyncIterator]()
next() returns{ value, done }Promise<{ value, done }>
Loop syntaxfor...offor await...of
Generator syntaxfunction*async function*
Typical sourcesArrays, Maps, Sets, stringsStreams, paginated APIs, event sources
Spread / destructuringSupportedNot supported directly

The for await…of loop

for await...of is the consumer side. It calls next(), awaits the promise, runs the body with the value, and repeats until done is true.

for await (const chunk of someAsyncIterable) {
  process(chunk);
}

Like await, it can only be used inside an async function or at the top level of an ES module. Each iteration fully finishes before the next next() call begins, so the loop is naturally sequential. If you need a refresher on why that matters, see async/await vs promises.

for await...of also accepts plain synchronous iterables. If the values are promises, each one is awaited in turn. That convenience comes with a trap covered below.

Writing async generators

Implementing the protocol by hand is tedious. Async generator functions do it for you. Declare the function with async function*, and inside it you can use both await and yield.

A classic use is walking a paginated API:

async function* fetchAllPages(url) {
  let next = url;
  while (next) {
    const res = await fetch(next);
    const body = await res.json();
    yield* body.items;
    next = body.nextPage;
  }
}

for await (const item of fetchAllPages("/api/orders")) {
  render(item);
}

The consumer has no idea pages exist. It sees a flat sequence of items, and the generator fetches the next page only when the loop asks for more. This is the core benefit of async iteration: the producer and consumer stay decoupled, and work happens lazily. The underlying requests use the standard Fetch API.

yield* delegates to another iterable, so yield* body.items emits each item in the page individually.

Laziness and backpressure for free

Because an async generator pauses at every yield until the consumer calls next() again, it never runs ahead of the code using its values. If rendering each item is slow, fetching slows down to match.

This is a simple, built-in form of backpressure. You do not need buffers, flags, or manual pause-and-resume logic. The pull-based design guarantees that a fast producer cannot overwhelm a slow consumer.

Cleanup when the loop exits early

If you break, return, or throw out of a for await...of loop, JavaScript calls the iterator’s return() method. For an async generator, that resumes the function as if a return statement had appeared at the paused yield, which means any finally block runs.

async function* readLines(file) {
  const handle = await openFile(file);
  try {
    for await (const line of handle.lines()) {
      yield line;
    }
  } finally {
    await handle.close();
  }
}

Stop reading after the first matching line, and the file still gets closed. This makes async generators a safe place to own resources like file handles, database cursors, or sockets. For cancellation that comes from outside the loop — a user navigating away, a timeout — pair this with an AbortController signal passed into the generator.

Built-in async iterables

You often do not need to write your own. Several platform APIs already implement Symbol.asyncIterator:

  • Node.js readable streams. Any readable stream can be consumed with for await...of, which is often the simplest way to read a file or HTTP body chunk by chunk. See Node.js streams explained.
  • Web ReadableStream. The Web Streams API defines async iteration on readable streams, so a fetch response body can be looped over directly in runtimes that support it. Check your target browsers before relying on it in frontend code.
  • Node.js events.on(). Turns an event emitter into an async iterable of events.
  • Node.js fs.promises.opendir(). Returns a directory handle you can iterate entry by entry.

Collecting results with Array.fromAsync

Sometimes you just want all the values in an array. Array.fromAsync() is the async counterpart to Array.from(): it consumes an async iterable (or a sync iterable of promises) and returns a promise for an array.

const orders = await Array.fromAsync(fetchAllPages("/api/orders"));

Use it only when the full result set fits comfortably in memory. If the source is large or unbounded, process items inside a loop instead.

Common pitfalls

  • Iterating an array of already-started promises. for await (const r of [p1, p2, p3]) awaits them in order. If p3 rejects before p1 settles, that rejection can surface as unhandled, because nothing is awaiting p3 yet. When you have a fixed set of promises, use Promise.all or Promise.allSettled instead.
  • Expecting parallelism. for await...of is strictly sequential. If each item triggers independent slow work, a plain loop processes them one at a time. Batch them deliberately if you need concurrency.
  • Forgetting it is pull-based. Nothing happens until someone iterates. Creating an async generator does not start any requests.
  • Spreading an async iterable. [...asyncIterable] does not work. Use Array.fromAsync() or a loop.

The takeaway

Async iterators wrap each next() result in a promise, and for await...of waits on each one in turn. Async generator functions make producing them as easy as writing a loop with await and yield, and they give you lazy evaluation, built-in backpressure, and reliable cleanup through finally. Reach for them whenever data arrives over time — pagination, streams, events — and reach for Promise.all when you already have a fixed set of independent promises.

Takina Takina · · 5 min read

Declarative Shadow DOM: Server-Rendered Web Components

Declarative Shadow DOM lets HTML create a shadow root with a template element, so web components can render on the server and display before JavaScript.

#Web Development #Frontend #JavaScript
Takina Takina · · 5 min read

Module Federation Explained: Sharing Code at Runtime

Module Federation lets separately built and deployed JavaScript apps load each other's modules at runtime. How hosts, remotes, and shared dependencies work.

#JavaScript #Frontend #Web Development