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;
}
}- ✓Correct answer: For lazily yielding data in chunks that arrive asynchronously
- 2For running requests in parallel in separate threads
- 3For synchronously waiting for a response without blocking the event loop
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.