×

javascript · level 3 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

loops over values that arrive over time.

Servers rarely send everything at once. A long list comes back in pages, called : ask for page 1, then page 2, until a page says there are no more. Writing that loop by hand, everywhere you need the list, gets messy.

An wraps it up: async function* can await a request, then yield each item. Whoever uses it writes for await...of, which waits for each value in turn. The paging logic stays hidden in one place.

async function* allProducts() {
  let page = 1;
  while (page !== null) {
    const reply = await fetch(`https://api.example.com/products?page=${page}`);
    const data = await reply.json();
    for (const item of data.items) { yield item; }
    page = data.next;
  }
}
for await (const product of allProducts()) {
  console.log(product);
}

Gwecode's practice server answers these page requests, and each page says which page comes next.