Перейти к основному содержимому
← ⚡ JavaScript & the browser·Модуль C6 · Урок 8
ЗаданиеWrite async function* fetchAllItems() that walks /api/items?page=<token>, yielding each item from items[], stopping when next is null. Consume with for-await-of and log every item.

Paginated fetch with async generator

200 XP12 min
Теория

The canonical async generator use case

You're consuming an API that returns paginated results: { items: [...], next: "<token>" }. Without async generators, this is a manual recursion + state mess. With them, it's a clean for-await loop.

async function* fetchAllItems() {
  let page = "1";
  while (page) {
    const r = await fetch(`/api/items?page=${page}`);
    const { items, next } = await r.json();
    for (const item of items) yield item;
    page = next;
  }
}

for await (const item of fetchAllItems()) {
  console.log(item); // each item, one at a time, across pages
}

The generator stops yielding when the API returns next: null. The consumer doesn't know or care how many pages there were.

Why this beats Promise.all

Promise.all loads ALL pages in parallel — you can't even start until you know how many there are. Async generators stream pages on demand. The first item is available after one request, not all.

Backpressure for free

If the consumer breaks out of the loop early, no more pages are requested. Sequential, lazy, cancellable — exactly the shape pagination wants.

🔒

Зарегистрируйся чтобы кодить

Теория открыта всем. Интерактивный редактор, живой превью и проверка открываются с 7-дневным бесплатным trial — нужна карта, отмена в любое время.

Регистрация — бесплатный trial →

Первые 10 уроков в каждом треке — бесплатные. Карта не нужна.

← НазадСледующий урок →

Получай один совет по Python или веб-разработке — каждый день в почте

Коротко, без воды, без спама. Отписаться — в один клик.