All posts
postApril 20, 2026

Async Iteration with for-await-of

#javascript#async#generators#iteration
Async Iteration with for-await-of — slide 1
javascript
async function* paginate(url) {
  let page = 1;
  while (true) {
    const res = await fetch(`${url}?page=${page}`);
    const data = await res.json();
    if (!data.items.length) return;
    yield data.items;
    page++;
  }
}

for await (const batch of paginate('/api/posts')) {
  console.log('Got batch:', batch.length);
  renderPosts(batch);
}