Async Iterators & for-await-of

Published by Brayan K

An async iterator is an object whose next() returns a promise of { value, done }, letting you pull values that arrive over time — one awaited step at a time — using the for-await-of loop.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Pull one asynchronous result at a time

An async iterable provides Symbol.asyncIterator. The iterator it returns has next(), whose result is awaited before the loop body receives a value. That protocol can express a page loader or stream reader without collecting every result first. It does not guarantee the producer does no background work; that depends on its implementation.

const events = [];
async function* values() {
  // Nothing in this body runs until the consumer requests a step.
  events.push("produce first");
  yield 3;
  events.push("produce second");
  yield 5;
}
const iterator = values();
console.log(events.length);
// Each awaited next receives a result record, not just the yielded value.
console.log(JSON.stringify(await iterator.next()));
console.log(events.join(", "));
console.log(JSON.stringify(await iterator.next()));
console.log(JSON.stringify(await iterator.next()));

// ✅ Expected output:
// 0
// {"value":3,"done":false}
// produce first
// {"value":5,"done":false}
// {"done":true}

done controls completion; a yielded undefined can still be an actual value with done false. An async generator returns an iterator that is normally consumed once. Call the generator function again for another independent traversal. Iterators & Iterables owns the synchronous protocol and cursor identity.

async function* values() { yield 2; yield 4; }
const iterator = values();
const first = [], second = [], fresh = [];
for await (const value of iterator) first.push(value);
for await (const value of iterator) second.push(value);
for await (const value of values()) fresh.push(value);
console.log(JSON.stringify([first, second, fresh]));

// ✅ Expected output:
// [[2,4],[],[2,4]]

Know what is awaited and what remains an ordinary value

const result = [];
for await (const value of [Promise.resolve(2), Promise.resolve(4)]) result.push(value);
console.log(JSON.stringify(result));

// ✅ Expected output:
// [2,4]
const source = {
  [Symbol.asyncIterator]() {
    let finished = false;
    return {
      async next() {
        if (finished) return { done: true };
        finished = true;
        return { done: false, value: Promise.resolve(7) };
      }
    };
  }
};
for await (const value of source) {
  console.log(value instanceof Promise);
  console.log(await value);
}

// ✅ Expected output:
// true
// 7

The loop awaits an async iterator’s next result. Its value field is then the value supplied by that iterator. The synchronous-to-async adapter unwraps yielded promises, and async generators also unwrap their yielded promise values. These related conveniences do not mean every custom async result field is recursively awaited.

async function* values() { yield Promise.resolve(7); }
for await (const value of values()) console.log(value, value instanceof Promise);

// ✅ Expected output:
// 7 false

The loop body completes before the next automatic next call. If you start several operations in advance and place their promises in an array, those operations may already overlap even though the loop observes them in order. Promise Combinators (all, race, allSettled, any) owns aggregate and bounded-concurrency policies.

Early exit and producer failure have different cleanup paths

const events = [];
const source = {
  [Symbol.asyncIterator]() {
    return {
      async next() { return { value: 3, done: false }; },
      async return() {
        await Promise.resolve();
        events.push("cleanup");
        return { done: true };
      }
    };
  }
};
for await (const value of source) { events.push("value " + value); break; }
events.push("after loop");
console.log(events.join(", "));

// ✅ Expected output:
// value 3, cleanup, after loop
const events = [];
async function* values() {
  try { yield 1; yield 2; }
  finally { events.push("released"); }
}
for await (const value of values()) { events.push("read " + value); break; }
console.log(events.join(", "));

// ✅ Expected output:
// read 1, released
let closed = false;
const source = {
  [Symbol.asyncIterator]() {
    return {
      next() { return Promise.reject(new Error("producer failed")); },
      async return() { closed = true; return { done: true }; }
    };
  }
};
try { for await (const value of source) console.log(value); }
catch (error) { console.log(error.message); }
console.log(closed);

// ✅ Expected output:
// producer failed
// false

A producer that fails while obtaining its next result must own its cleanup. Do not assume return is called for every possible failure. Current runtimes close a synchronous generator when its yielded promise rejects through the async adapter, while older runtimes can leave its finally block unrun. For cleanup that also works across those older runtimes, explicitly await values inside a normal for-of loop whose abrupt body exit closes that synchronous iterator. Prefer an async generator when the producer itself is asynchronous.

const events = [];
function* values() {
  try { yield Promise.reject(new Error("failed value")); }
  finally { events.push("released"); }
}
try { for (const promise of values()) await promise; }
catch (error) { events.push(error.message); }
console.log(events.join(", "));

// ✅ Expected output:
// released, failed value

Returning an iterator is not an interrupt for an active await

let release;
const gate = new Promise(resolve => { release = resolve; });
const events = [];
async function* values() {
  try { await gate; yield 1; }
  finally { events.push("cleanup"); }
}
const iterator = values();
const pending = iterator.next();
let closed = false;
const closing = iterator.return().then(result => { closed = true; return result; });
await Promise.resolve();
console.log(closed);
release();
console.log(JSON.stringify(await pending));
console.log(JSON.stringify(await closing), events.join(", "));

// ✅ Expected output:
// false
// {"value":1,"done":false}
// {"done":true} cleanup

The return request is queued behind the active next request. An underlying fetch or wait needs its own cooperative cancellation mechanism if it must stop promptly. AbortController & Cancelling Async Work owns that mechanism. Do not label the return call itself as an immediate network cancellation.

Guided exercise: consume until a deliberate boundary

Fill the literal hints to read only the first two values. The generator’s finally block shows that the break closes this producer.

const values = [];
async function* source() {
  try { yield 2; yield 4; yield 6; }
  finally { console.log("closed"); }
}
for ___ (const value of source()) { // 👉 replace ___ with await
  values.push(value);
  if (values.length === ___) break; // 👉 replace ___ with 2
}
console.log(JSON.___(values)); // 👉 replace ___ with stringify

// ✅ Expected output:
// closed
// [2,4]

Brief: page lazily, validate before yielding and bound the requests

Implement pagedValues(loadPage, maxPages = 10). Validate the loader and integer page limit 1–10 immediately when the factory is called, then return a one-use async iterator. Start with cursor null and request one page only when consumption needs it. Each loader result must be an ordinary non-array object with a dense items array of at most 100 safe integers from 0 through 1000, and nextCursor null or 1–20 lowercase ASCII letters/digits.

Validate and snapshot the entire page before yielding any of its items. Reject a next cursor already requested, including an immediate repeat, before yielding the invalid page. A null next cursor ends traversal. Empty pages may lead to another cursor. Never prefetch a later page, and never call the loader more than maxPages times. If consumption asks past that budget while another page remains, throw RangeError("page limit reached").

Propagate loader failures. Early break must prevent further page requests; it cannot undo the request that already produced the current page. Ordinary JSON data is assumed, so hostile getters or proxies are outside this contract. This is an injected loader example, not a claim about any live API.

function pagedValues(loadPage, maxPages = 10) {
  if (typeof loadPage !== "function") throw new TypeError("loader must be a function");
  if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 10) throw new RangeError("invalid page limit");
  return (async function* () {
    let cursor = null, requests = 0;
    const seen = new Set();
    while (true) {
      if (requests >= maxPages) throw new RangeError("page limit reached");
      seen.add(cursor);
      requests++;
      const page = await loadPage(cursor);
      if (page === null || typeof page !== "object" || Array.isArray(page) ||
          !Array.isArray(page.items) || page.items.length > 100) throw new TypeError("invalid page");
      const items = [];
      for (let i = 0; i < page.items.length; i++) {
        if (!Object.hasOwn(page.items, i) || !Number.isSafeInteger(page.items[i]) ||
            page.items[i] < 0 || page.items[i] > 1000) throw new TypeError("invalid page item");
        items.push(page.items[i]);
      }
      const next = page.nextCursor;
      if (next !== null && (typeof next !== "string" || !/^[a-z0-9]{1,20}$/.test(next))) {
        throw new TypeError("invalid next cursor");
      }
      if (next !== null && seen.has(next)) throw new RangeError("cursor cycle");
      for (const item of items) yield item;
      if (next === null) return;
      cursor = next;
    }
  })();
}
const calls = [];
const loader = async cursor => {
  calls.push(cursor === null ? "start" : cursor);
  return cursor === null ? { items: [2, 4], nextCursor: "next" }
    : { items: [6], nextCursor: null };
};
const iterator = pagedValues(loader);
console.log(calls.length);
console.log(JSON.stringify(await iterator.next()), calls.join(", "));
await iterator.return();
console.log(calls.join(", "));
const all = [];
for await (const value of pagedValues(loader)) all.push(value);
console.log(JSON.stringify(all));
try {
  for await (const value of pagedValues(async () => ({ items: [1, "bad"], nextCursor: null }))) {
    console.log("must not yield", value);
  }
} catch (error) { console.log(error.name, error.message); }

// ✅ Expected output:
// 0
// {"value":2,"done":false} start
// start
// [2,4,6]
// TypeError invalid page item

Practice quiz

What does this complete program print? async function* values(){yield 3;}const it=values();console.log(JSON.stringify(await it.next()));

  • {"value":3,"done":false}
  • 3
  • {"done":true}
  • {}

Answer: {"value":3,"done":false}. next resolves to a result record with value and done.

What does this complete program print? async function* values(){yield 1;}const it=values();await it.next();console.log((await it.next()).done);

  • false
  • true
  • undefined
  • TypeError

Answer: true. The second request reaches completion.

What does this complete program print? const out=[];for await(const value of [Promise.resolve(2),Promise.resolve(3)])out.push(value);console.log(JSON.stringify(out));

  • [{},{}]
  • []
  • [2,3]
  • TypeError

Answer: [2,3]. The synchronous iterable adapter unwraps the yielded promises.

What does this complete program print? const events=[];async function* values(){try{yield 1;yield 2;}finally{events.push("closed");}}for await(const n of values()){events.push(n);break;}console.log(events.join(","));

  • 1,2,closed
  • 1
  • closed,1
  • 1,closed

Answer: 1,closed. Breaking closes this generator and runs its finally block.

What does this complete program print? async function* values(){yield 2;}const it=values();for await(const n of it){}let count=0;for await(const n of it)count++;console.log(count);

  • 0
  • 1
  • 2
  • TypeError

Answer: 0. The same exhausted iterator does not restart.

What does this complete program print? async function* values(){yield Promise.resolve(4);}for await(const value of values())console.log(value,typeof value);

  • [object Promise] object
  • 4 number
  • 4 object
  • undefined undefined

Answer: 4 number. Async generators unwrap their yielded promise values.

What does this complete program print? let calls=0;async function* values(){calls++;yield 1;}const it=values();console.log(calls);await it.next();console.log(calls);

  • 1 1
  • 0 0
  • 0 1
  • 1 2

Answer: 0 1. Creating the generator does not execute its body.

What does this complete program print? async function* values(){yield undefined;}const result=await values().next();console.log(result.done,result.value===undefined);

  • true true
  • false false
  • true false
  • false true

Answer: false true. An undefined value can be a real yielded item; done determines completion.

Continue this course

Related lessons