Async Iterators
for await...of and async generators
async function* paginate(pageSize) {
for (let page = 1; page <= 3; page++) {
// Simulate API call
await new Promise(r => setTimeout(r, 50));
const items = Array.from(
{ length: pageSize },
(_, i) => `page${page}-item${i + 1}`,
);
console.log(`fetched page ${page}`);
for (const item of items) yield item;
}
}
(async () => {
// Stream every item across all pages
for await (const item of paginate(3)) {
console.log("got:", item);
}
// Early exit
console.log("--- with break ---");
for await (const item of paginate(3)) {
console.log("scan:", item);
if (item === "page2-item2") break;
}
})();