Skip to content
jshacks.dev
Functions

Write an async generator

Write an async generator in JavaScript with async function*, which awaits between yields to produce values over time, such as pages of results.

1 min read
Summarize in AI

Paged APIs and event streams produce values over time. An async function* can await in its body and still yield items one by one.

JavaScript
async function* pages(total) {
  for (let page = 1; page <= total; page++) {
    await new Promise((resolve) => setTimeout(resolve, 10));
    yield { page, items: [page * 10, page * 10 + 1] };
  }
}

const gen = pages(2);
console.log(await gen.next());
console.log(await gen.next());
console.log(await gen.next());
Text
{ value: { page: 1, items: [ 10, 11 ] }, done: false }
{ value: { page: 2, items: [ 20, 21 ] }, done: false }
{ value: undefined, done: true }

Each next() returns a promise for the usual { value, done } result, which is why every call is awaited. The code above uses top-level await, so save it as an ES module such as pages.mjs. An async generator pauses at each yield until the consumer asks for the next item, so a slow consumer applies backpressure by itself.

Calling next() twice without awaiting queues the requests in order. In real code you will usually read an async generator with for await, shown in the next snippet, and not by hand.

Also inAsync
Taggednode 24
Share

More snippets

Functions

Memoize a function with a Map

Memoize a function in JavaScript with a Map keyed by its argument, caching results including undefined. For single-argument pure functions on any Node.js.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 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.