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.
Paged APIs and event streams produce values over time. An async function* can await in its body and still yield items one by one.
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());{ 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.