Blog Hoch
Apr 2026·1 tup leghDe'wI' chenmoHta'

JavaScript Async Iterators 'ej Generators

#javascript#async

for...of loops arrays 'ej iterables wa' value poH wa'. for await...of rap, value Hoch poH poQ - paginated API results laD, file tIn stream, events qaS. promises manual juggle pagh. 'ach generators mIw. generator ghItlh laH vaj "stream Dochmey process" code Dun.

regular generators: pausable functions

generator function (function*) yield pause 'ej tlhoy' resume, local state Dach.

function* countTo(n) {
  for (let i = 1; i <= n; i++) {
    yield i;
  }
}

for (const value of countTo(3)) {
  console.log(value); // 1, 2, 3
}

countTo(3) function body Qu'be' - iterator nob. .next() Hoch (for...of Qu') function wa'DIch yield Qu', value nob, pause. 'oH mIw: function resume laH (start-to-finish neH pagh).

async generators: same idea, await rap

async generator (async function*) yield qaSpa' await laH. value Hoch asynchronous operation Dung: network request, database query, timer.

async function* fetchAllUsers() {
  let page = 1;
  while (true) {
    const response = await fetch(`/api/users?page=${page}`);
    const { users, hasMore } = await response.json();

    yield* users; // yield each user individually, not the whole page

    if (!hasMore) return;
    page++;
  }
}
for await (const user of fetchAllUsers()) {
  console.log(user.name);
}

consumer pagination Sov pagh. user objects wa' stream legh, wa'-wa' process. generator paging loop, fetch calls, "Qu'pu''a'" logic Hoch hide.

promises array nob Qatlh?

alternative: pages Hoch fetch, Promise.all, flatten - Qu' 'ach dataset Hoch memory Daq hold, pages Hoch wait qaSpa' wa'DIch record process. async generator value ready vaj yield:

// Eager: waits for everything, holds it all in memory
async function fetchAllUsersEager() {
  const pages = await Promise.all(
    pageNumbers.map((p) => fetch(`/api/users?page=${p}`).then((r) => r.json())),
  );
  return pages.flatMap((p) => p.users);
}

// Lazy: starts producing values immediately, one page at a time
async function* fetchAllUsersLazy() {
  // ...as above
}

10,000 users 100 pages: eager version user #1 process laHbe' (100 requests Hoch Qu'). generator version page 1 ghoS vaj user #1 process. consumer 20 users neH poQ vaj early stop, generator pages 2-100 fetch pagh.

early stop work Qaw'

for await...of loop break vaj generator .return() Qu' 'ej pending finally blocks Qu'. resources clean release.

async function* readLines(filePath) {
  const fileHandle = await openFile(filePath);
  try {
    let line;
    while ((line = await fileHandle.readLine()) !== null) {
      yield line;
    }
  } finally {
    console.log('closing file handle');
    await fileHandle.close();
  }
}

for await (const line of readLines('access.log')) {
  if (line.includes('ERROR')) {
    console.log('found it:', line);
    break; // triggers the generator's finally block — file still gets closed
  }
}

generator finally pagh vaj early break file handle open Dach. regular try/finally guarantee rap, resource lifetime multiple await points span.

async iterable mach

Symbol.asyncIterator implement Hoch for await...of Daq Qu'. generator function poQ pagh (Dun 'ach). values over time produce 'ach generators pagh wrap vaD Dun: WebSocket message stream:

function messagesFrom(socket) {
  return {
    [Symbol.asyncIterator]() {
      const queue = [];
      let resolveNext;

      socket.addEventListener('message', (event) => {
        if (resolveNext) {
          resolveNext({ value: event.data, done: false });
          resolveNext = null;
        } else {
          queue.push(event.data);
        }
      });

      return {
        next() {
          if (queue.length > 0) {
            return Promise.resolve({ value: queue.shift(), done: false });
          }
          return new Promise((resolve) => { resolveNext = resolve; });
        },
      };
    },
  };
}
for await (const message of messagesFrom(socket)) {
  console.log('received:', message);
}

event-emitter style API loop directly choH. callback register pagh, state manual manage pagh.

nuq lo'

async generators Dun values sequence over time process 'ej consumer chay' arrive Sov poQ pagh: pagination, streaming responses, chunked file reads, WebSocket/SSE streams. full dataset ghaj vaj (wa' fetch result) plain array 'ej for...of Dun. async function* "next value produce" wait poQ vaj lo'.

chu'WebSockets mach yajqanJavaScript Memoization, useMemo Dung