Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C6 · Урок 7
ЗавданняWrite async function* ticks() that yields 1, 2, 3, each preceded by await new Promise(r => setTimeout(r, 5)). Consume with for-await-of and log each value. Then await the generator into an array via for-await + push, log the joined array.

Async generators — async function*

175 XP11 min
Теорія

A stream of values that arrive over time

An async function* yields Promises that resolve to the next value. You consume them with for await...of.

async function* ticks() {
  for (let i = 1; i <= 3; i++) {
    await new Promise(r => setTimeout(r, 10));
    yield i;
  }
}

for await (const v of ticks()) {
  console.log(v); // 1, then 10ms later 2, then 10ms later 3
}

Why this is huge

The same iteration protocol that powers for-of over arrays now powers paginated APIs, server-sent events, file-by-file directory walks. One mental model.

Inside vs outside

Inside the generator: you can await whatever you want before yielding — fetch, sleep, database round-trip.

Outside: you walk it with for await. Same shape as for-of. Same break/continue rules.

Top-level await

Module scripts (<script type="module">) allow top-level await. That's how the task below consumes the async generator without wrapping it in another async function.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.