Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Compose async generators in JavaScript

13 An async generator, and composing two of them

fair

Write an async function* that reads rows from a fake store, and a second one that filters the first. Prove the pipeline is lazy by counting reads, and check what an async generator object does and does not have on it.

Stuck? Three hints, smallest first
  1. 1. async function* lets you await inside and yield out. Consume it with for await.
  2. 2. Chain them by passing one async generator into the for await of the next.
  3. 3. It supplies Symbol.asyncIterator and, deliberately, no Symbol.iterator.

The answer

const store = {
  rows: [
    { plate: 'LAG-441-XA', fee: 2500 },
    { plate: 'ABJ-772-KM', fee: 4000 },
    { plate: 'KAN-118-QQ', fee: 1500 },
  ],
  // Pretend I/O. It resolves at once, so nothing here waits on real time.
  read(i) { return Promise.resolve(this.rows[i]); },
};

async function* rowsOf(source) {
  for (let i = 0; i < source.rows.length; i++) yield await source.read(i);
}

async function* feesOver(source, limit) {
  for await (const row of source) if (row.fee > limit) yield row.plate;
}

const collect = async (source) => {
  const out = [];
  for await (const v of source) out.push(v);
  return out;
};

const big = await collect(feesOver(rowsOf(store), 2000));
const all = await collect(feesOver(rowsOf(store), 100));

let reads = 0;
const metered = { rows: store.rows, read(i) { reads++; return Promise.resolve(this.rows[i]); } };
const lazily = feesOver(rowsOf(metered), 2000);
const firstOne = await lazily.next();
const readsAfterOne = reads;

console.log('over ₦2000 :', big);
console.log('everything :', all);
console.log('one value out cost', readsAfterOne, 'read(s)');

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('an async generator is consumed with for await', big, ['LAG-441-XA', 'ABJ-772-KM']);
test('and two of them compose like sync ones', all, ['LAG-441-XA', 'ABJ-772-KM', 'KAN-118-QQ']);
test('calling one returns an async iterator, not a promise', typeof rowsOf(store)[Symbol.asyncIterator], 'function');
test('its next() resolves to the usual result object', await rowsOf(store).next(), { value: { plate: 'LAG-441-XA', fee: 2500 }, done: false });
test('the pipeline is lazy: one value out, one read in', [firstOne.value, readsAfterOne], ['LAG-441-XA', 1]);
test('it has no Symbol.iterator, so for...of cannot take it', typeof rowsOf(store)[Symbol.iterator], 'undefined');
test('the last next reports done', (await collect(rowsOf(store))).length, 3);
test('an async generator that yields nothing is simply empty', await collect((async function* () {})()), []);

async function* is the two features stacked: await for waiting, yield for producing, and the result is a pull-based stream where each pull may take time. That is the right shape for anything that arrives in pieces — paged responses, lines of a file, messages off a socket — because the consumer sets the pace.

The laziness assertion is the practical consequence. feesOver(rowsOf(metered), 2000).next() performed exactly one read. An eager version would have fetched all three before the caller looked at any of them, which on a hundred-page API is a hundred requests for a value you may discard after the first.

Note the deliberate absence of Symbol.iterator. An async generator cannot pretend to be synchronous — its values are not available yet — so for...of and spread reject it outright rather than handing you promises. That refusal is a feature: the alternative is an array of pending promises that looks like data.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.