JavaScript · Senior · Question 7 of 75

What is an async generator handy for?

async function* pages(url) {
  while (url) {
    const res = await fetch(url).then(r => r.json());
    yield res.items;
    url = res.next;
  }
}

Explanation

The consumer writes for await (const items of pages(url)) and decides when to stop - the next page isn't requested until it's needed. Leaving the loop with break calls the generator's return() and finishes it.

Further reading

Problem with a question

JavaScript · Senior · question 7

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz