Data that arrives in pieces
Paged APIs, chat messages, file downloads — data often arrives over time. Async generators produce values that take time, and for await…of consumes them as they come.
async function* and for await
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function* pages() {
for (let page = 1; page <= 3; page++) {
await sleep(100);
yield [`item ${page}a`, `item ${page}b`];
}
}
async function main() {
for await (const items of pages()) {
console.log("got", items);
}
console.log("all pages loaded");
}
main();Async generators are perfect for "load page after page until there are no more" — the caller just loops and never sees the paging logic.