Ugrás a fő tartalomra
← ⚡ JavaScript & the browser·Modul C4 · Lecke 8
FeladatBuild async generator stream() that yields 'a', then 'b', then 'c' (with a 0ms timeout between to be properly async). Iterate over it with for-await-of and log each.

for-await-of: iteráció aszinkron források felett

100 XP8 min
Elmélet

Iterating over Promises sequentially

const urls = ["/api/a", "/api/b", "/api/c"];

for await (const url of urls.map(u => fetch(u))) {
  console.log(url.status);
}

for-await-of walks an iterable of Promises and awaits each one in order. If you need sequence (e.g. each fetch depends on a previous redirect), this is cleaner than for + await.

Reading a stream of chunks

The real superpower: any object with an async iterator works. ReadableStreams expose one:

const r = await fetch("/api/long-text");
const reader = r.body.pipeThrough(new TextDecoderStream());

for await (const chunk of reader) {
  console.log("chunk:", chunk.slice(0, 50));
}

That's how you stream an OpenAI / Anthropic response token-by-token in the browser. fetch gives you a ReadableStream; you pipe through TextDecoderStream to get strings; for-await-of reads chunks as they arrive.

Building your own async iterator

async function* range(start, end) {
  for (let i = start; i < end; i += 1) {
    await new Promise(r => setTimeout(r, 100));   // simulate async work
    yield i;
  }
}

for await (const n of range(1, 4)) {
  console.log(n);   // 1, then 2 (100ms later), then 3
}

async function* is the syntax. yield produces values, await pauses between them.

🔒

Regisztrálj, hogy elkezdj programozni

Az elmélet mindenkinek nyitva. A szerkesztő, élő előnézet és ellenőrzés 7 napos ingyenes próbával nyílik meg — kártya szükséges, bármikor lemondható.

Regisztráció — ingyenes próba →

Minden útvonal első 10 leckéje ingyenes. Nem kell kártya.

← ElőzőKövetkező lecke →

Egy Python- vagy webes tipp naponta — emailben

Rövid, kézzel írt, spam nélkül. Egy kattintással leiratkozhatsz.