>catasync-iterators-in-javascript.md

Async Iterators in JavaScript

Async generators, for-await loops and streams as a means of handling data incrementally.

date

ES2018 gave JavaScript async iterators, which allow streaming data to be consumed with the familiar for await...of syntax. They combine async/await with the iterator protocol so that chunks of data are pulled on demand, which suits paginated APIs, streaming responses and files read in chunks.

The protocols

The AsyncIterator interface underlies all of this. Written out by hand, an async iterator looks like this:

const asyncIterator = {
  async next() {
    // Returns Promise<{value, done}>
    return { value: someValue, done: false };
  },
  async return(value) {
    // Optional cleanup method
    return { value, done: true };
  },
  async throw(exception) {
    // Optional error handling
    return Promise.reject(exception);
  }
};

Iteration is governed by two complementary protocols, which mirror the synchronous ones with promises in place of plain values. An object is async iterable when it has a [Symbol.asyncIterator]() method that returns an async iterator. It is an async iterator when it has the following methods:

  • next(), which returns a promise that fulfils to an object with {value, done} properties;
  • return(value) (optional), which returns a promise for cleanup that fulfils to {value, done: true};
  • throw(exception) (optional), which returns a promise for error handling.

An iterable that satisfies both protocols, consumed with for await:

const asyncIterable = {
  [Symbol.asyncIterator]() {
    let count = 0;
    return {
      async next() {
        if (count < 3) {
          return { value: count++, done: false };
        }
        return { done: true };
      }
    };
  }
};

for await (const value of asyncIterable) {
  console.log(value); // 0, 1, 2
}

Async generators

Writing iterators by hand is rarely necessary. The async function* syntax declares an async generator function, which returns an async iterator; the * marks a generator, and async makes it asynchronous:

// Yields pages from a paginated API
async function* fetchPages(endpoint, limit = 3) {
  let page = 1;
  while (true) {
    const res = await fetch(`${endpoint}?page=${page}`);
    if (!res.ok) break;
    const data = await res.json();
    if (!data.items?.length) break;
    yield data.items;
    if (page++ >= limit) break;
  }
}

fetchPages pauses at each yield until the consumer asks for the next chunk. for await is that consumer: it requests values one at a time and awaits each promise the iterator returns.

for await (const items of fetchPages('/api/posts')) {
  for (const item of items) {
    console.log('post', item.id);
  }
}

Piping streams

Readable streams in Node 18+ are async iterable, so transforms can be chained as async generators:

async function* filterLines(source, predicate) {
  for await (const chunk of source) {
    const lines = chunk.toString().split('\n');
    for (const line of lines) {
      if (predicate(line)) yield line;
    }
  }
}

const fs = await import('node:fs');
const stream = fs.createReadStream('access.log', { encoding: 'utf8' });

for await (const line of filterLines(stream, l => l.includes('ERROR'))) {
  console.log(line);
}

Since the consumer pulls, backpressure is a matter of how fast the loop runs, and the pipeline composes from ordinary loops rather than nested callbacks.

A fetch response exposes body as a ReadableStream, which the Streams specification makes async iterable, so that for await can be used on res.body directly. Node and Firefox support this, but browser support is not yet uniform, and portable code may still need to call getReader() and loop over read(). In Node, most modern readable streams are async iterable, and legacy ones can be wrapped with Readable.from. In either case, errors from awaited operations surface inside the loop, so the for await belongs inside a try/catch.

Syntax

  • async / await
  • for await...of
  • function*
  • Promise, on which async iteration rests.