Sikau

Advanced JavaScript · Day 21 · about 25 min

Async iteration

for await…of and async generators.

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.

The rest of this lesson

  • Paging made invisibleexplain
  • When to reach for itexplain
  • Predict the outputpredict
  • Collecting an async generatorpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript