Async Iterator next() Method
You'll learn: How the next() method in async iterators must return a promise that resolves to an iteration result object.
In synchronous iterators, calling next() immediately returns an object like {value: something, done: false}. But async iterators deal with values that aren't immediately available—they might come from a network request, a file read, or a delayed operation. So the next() method must return a promise that eventually resolves to that same {value, done} shape.
Think of it like ordering food: a sync iterator is a buffet (you grab food immediately), while an async iterator is table service (you get a receipt/promise, then wait for your order to arrive).
The Contract
When you call next() on an async iterator, three things happen:
- You get back a Promise right away
- That promise resolves to an object with
valueanddoneproperties - If
doneisfalse, there's more data coming; iftrue, iteration is complete
const asyncIterator = {
current: 0,
[Symbol.asyncIterator]() { return this; },
next() {
if (this.current < 3) {
// Return a promise resolving to the result
return Promise.resolve({
value: this.current++,
done: false
});
}
return Promise.resolve({ done: true });
}
};
// Using it:
for await (const num of asyncIterator) {
console.log(num); // 0, 1, 2
}
The key difference from sync iterators: next() returns Promise<{value, done}> instead of just {value, done}.
Key Takeaway: The async iterator's next() method must always return a promise that resolves to an iteration result object containing value and done properties, enabling asynchronous data streams.