for await...of
Async iterables yield values asynchronously. Use for await...of to consume streams, paginated APIs, and async generators.
Async iterables yield values asynchronously. Use for await...of to consume streams, paginated APIs, and async generators.
async function* paginate(url) {
let page = 1, hasMore = true;
while (hasMore) {
const { data, next } = await fetch(`${url}?page=${page}`).then(r => r.json());
yield data;
hasMore = !!next; page++;
}
}
for await (const batch of paginate("/api/items")) {
processBatch(batch);
}
Async generators + for await...of are the idiomatic way to consume streaming or paginated data.
More in JavaScript