Sub topic 7
Building an Async Iterable by Hand
This chapter assumes you already know the async iteration protocol, how for await...of consumes it, and how an early break calls return(). Most of the time an async function* is the simplest way to produce an async sequence. Writing the protocol yourself is still worth learning, for two reasons. Some sources, such as event emitters, sockets, and message queues, push values at you instead of waiting to be asked, and a generator does not fit them well. When you build the object yourself, you also see exactly what a generator was doing for you.
The Minimum Shape
An async iterable is any object with a [Symbol.asyncIterator] method. That method returns an async iterator: an object whose next() method returns a Promise that resolves to an iterator result { value, done }. An iterator can also have a return() method, which the loop calls when it exits early.
const ticker = {
[Symbol.asyncIterator]() {
let count = 0;
return {
next() {
count++;
if (count > 3) {
return Promise.resolve({ value: undefined, done: true });
}
return new Promise((resolve) =>
setTimeout(() => resolve({ value: count, done: false }), 100)
);
},
return() {
console.log('cleanup');
return Promise.resolve({ value: undefined, done: true });
}
};
}
};
async function main() {
for await (const tick of ticker) {
console.log(tick);
if (tick === 2) break; // calls return(), logs 'cleanup'
}
}
main();The output is 1, 2, cleanup. The state (count) is stored in a closure created by each call to [Symbol.asyncIterator](). As a result, every for await...of loop over ticker starts again from zero.
The diagram below shows the calls for await...of makes on this object.
Using async Methods to Avoid Promise Plumbing
You don't have to wrap every result in Promise.resolve. If you declare next as an async method, it always returns a Promise, and anything it throws becomes a rejection. The for await...of loop turns that rejection into an exception you can catch with try/catch.
class AsyncRange {
constructor(from, to, delayMs) {
this.from = from;
this.to = to;
this.delayMs = delayMs;
}
[Symbol.asyncIterator]() {
let current = this.from;
const { to, delayMs } = this;
return {
async next() {
if (current > to) return { value: undefined, done: true };
await new Promise((resolve) => setTimeout(resolve, delayMs));
return { value: current++, done: false };
},
async return() {
current = to + 1; // later next() calls report done
return { value: undefined, done: true };
}
};
}
}
async function main() {
const range = new AsyncRange(1, 3, 50);
for await (const n of range) console.log('first pass', n);
for await (const n of range) console.log('second pass', n);
}
main();Both loops print 1, 2, 3. That works because the class makes a fresh iterator every time [Symbol.asyncIterator]() is called. This is called a reusable iterable. An async generator object behaves the other way: its [Symbol.asyncIterator]() returns this, so it can be consumed only once.
Iterator-Is-Its-Own-Iterable
A common pattern is an object that is both the iterable and the iterator, with [Symbol.asyncIterator]() { return this; }. This fits sources that can only be read once, such as a network connection. It also lets you pass the iterator straight to for await...of after you have already called next() on it by hand. The trade-off is that a second loop continues from where the first one stopped, or gets nothing if the first loop called return().
| Design | `[Symbol.asyncIterator]()` returns | Second loop sees | Good for |
|---|---|---|---|
| Reusable iterable | A new iterator object | The full sequence again | Ranges, replayable queries |
| Self-iterator | `this` | What is left, often nothing | Streams, sockets, queues |
| Async generator object | `this` | Nothing once finished or closed | Most producer code |
A Push-Based Source: An Async Queue
Generators pull values: each next() call runs the body until the next yield. Event sources push values whenever they like. To connect a push source to for await...of, you need a buffer for values that arrive before anyone asks for them. You also need a list of waiting consumers for requests that arrive before any value exists.
class AsyncQueue {
#values = [];
#waiters = [];
#closed = false;
push(value) {
if (this.#closed) throw new Error('queue is closed');
const resolve = this.#waiters.shift();
if (resolve) resolve({ value, done: false });
else this.#values.push(value);
}
close() {
this.#closed = true;
for (const resolve of this.#waiters.splice(0)) {
resolve({ value: undefined, done: true });
}
}
next() {
if (this.#values.length > 0) {
return Promise.resolve({ value: this.#values.shift(), done: false });
}
if (this.#closed) {
return Promise.resolve({ value: undefined, done: true });
}
return new Promise((resolve) => this.#waiters.push(resolve));
}
return() {
this.close();
this.#values.length = 0; // drop anything still buffered
return Promise.resolve({ value: undefined, done: true });
}
[Symbol.asyncIterator]() {
return this;
}
}
async function main() {
const queue = new AsyncQueue();
setTimeout(() => queue.push('a'), 50);
setTimeout(() => queue.push('b'), 100);
setTimeout(() => queue.close(), 150);
for await (const v of queue) console.log(v);
console.log('done'); // a, b, done
}
main();The queue handles three cases:
- A value arrives and a consumer is already waiting. The value goes straight to the oldest waiting consumer.
- A value arrives and nobody is waiting. The value is buffered until the next
next()call. - The queue closes. Every waiting consumer receives
done: true, and so does every later call.
Overlapping next() calls
for await...of never calls next() again until the previous Promise has settled. Code that calls next() directly has no such limit. An async generator queues overlapping calls internally. A hand-built iterator has to handle them itself. The queue above does, because each pending call gets its own slot in #waiters, in order:
// Paste below the AsyncQueue class
async function overlapping() {
const q = new AsyncQueue();
const first = q.next();
const second = q.next();
q.push(1);
q.push(2);
q.close();
console.log(await first, await second, await q.next());
// { value: 1, done: false } { value: 2, done: false } { value: undefined, done: true }
}
overlapping();A naive design keeps a single pendingResolve variable. A second overlapping call overwrites it, and the first Promise never settles. A consumer awaiting a Promise that never settles hangs without any error, which makes this bug hard to find.
Wrapping an Event Emitter
The queue turns into a reusable adapter once you connect it to events and remove the listeners in return(). That is the cleanup a generator would otherwise do in its finally block.
import { EventEmitter } from 'node:events';
function eventsOf(emitter, dataEvent, endEvent) {
const values = [];
const waiters = [];
let finished = false;
const onData = (value) => {
const resolve = waiters.shift();
if (resolve) resolve({ value, done: false });
else values.push(value);
};
const finish = () => {
if (finished) return;
finished = true;
emitter.off(dataEvent, onData);
emitter.off(endEvent, finish);
for (const resolve of waiters.splice(0)) {
resolve({ value: undefined, done: true });
}
};
emitter.on(dataEvent, onData);
emitter.on(endEvent, finish);
return {
[Symbol.asyncIterator]() { return this; },
next() {
if (values.length > 0) {
return Promise.resolve({ value: values.shift(), done: false });
}
if (finished) return Promise.resolve({ value: undefined, done: true });
return new Promise((resolve) => waiters.push(resolve));
},
return() {
finish();
values.length = 0;
return Promise.resolve({ value: undefined, done: true });
}
};
}
const emitter = new EventEmitter();
setTimeout(() => emitter.emit('msg', 'hello'), 20);
setTimeout(() => emitter.emit('msg', 'world'), 40);
setTimeout(() => emitter.emit('msg', 'ignored'), 60);
for await (const msg of eventsOf(emitter, 'msg', 'end')) {
console.log(msg);
if (msg === 'world') break;
}
console.log('listeners left:', emitter.listenerCount('msg')); // 0Save this as an .mjs file so the top-level for await works. After the break, return() removes both listeners, so the emitter no longer holds a reference to the closed iterator. Node.js ships a built-in version of this adapter, events.on(). A later chapter covers it.
Gotchas Specific to Hand-Written Iterators
The value is not awaited
When for await...of reads a real async iterator, it awaits the Promise returned by next(), but it does not await value. If you put a Promise in value, the loop variable is that Promise:
const sneaky = {
[Symbol.asyncIterator]() {
let sent = false;
return {
next() {
if (sent) return Promise.resolve({ value: undefined, done: true });
sent = true;
return Promise.resolve({ value: Promise.resolve(42), done: false });
}
};
}
};
async function main() {
for await (const v of sneaky) console.log(v); // Promise { 42 }
}
main();An async generator does not have this problem, because yield awaits its operand first. Sync iterables used with for await...of don't have it either, because the loop wraps them in an adapter that awaits each value. Hand-written async iterators get no such help, so resolve the value before you put it in the result.
Results must be objects
If next() resolves to something that is not an object, such as undefined because you forgot a return, the loop throws TypeError: Iterator result undefined is not an object. The same rule applies to whatever return() resolves to when the loop exits early.
Which methods the loop calls
| Method | Required | Called by `for await...of` when |
|---|---|---|
| `next()` | Yes | Every iteration |
| `return()` | No | The body runs `break` or `return`, or throws |
| `throw()` | No | Never. `yield*` delegation forwards errors to it |
The loop does not call return() when next() rejects or reports done: true. In that case the iterator has finished itself and has to clean up its own resources before rejecting or reporting done.
Exercises
Exercise
A hand-built iterator stores a single variable, pendingResolve, and its next() returns new Promise((r) => { pendingResolve = r; }) whenever no value is buffered. Why does this work with for await...of but fail when two next() calls are made back to back without awaiting?
Show answer
for await...of waits for each next() Promise to settle before calling next() again, so at most one request is ever pending. Two overlapping manual calls both assign to pendingResolve. The second assignment overwrites the first resolver, so the first Promise never settles and its awaiting code hangs. The fix is to keep an array of resolvers and resolve them in order, as AsyncQueue does.
Exercise
Change the AsyncRange class so that iterating it twice at the same time (two loops started together) still gives each loop the full sequence 1 to 3. What, if anything, has to change?
Show answer
Nothing has to change. Each call to [Symbol.asyncIterator]() creates a new closure with its own current variable, so two loops running at the same time get independent iterators. The design would break only if current were stored on the AsyncRange instance (this.current), because then both loops would share and advance one counter.
Exercise
In the eventsOf adapter, the emitter emits 'end' while a for await...of loop is waiting inside next(). Trace what happens, and say whether return() is called.
Show answer
The 'end' handler runs finish(). It sets finished to true, removes both listeners, and resolves the waiting Promise with { value: undefined, done: true }. The loop receives done: true and exits normally. return() is not called, because the iterator finished on its own. That is why finish() has to do the cleanup itself instead of relying on return().