The Async Iterator Protocol
What you'll learn: The exact contract an async iterator must fulfill to work with for await...of and other async iteration mechanisms.
The Core Contract
Just like the regular iterator protocol defines how synchronous iterators work, the async iterator protocol specifies the rules for asynchronous iteration. An object becomes an async iterator when it implements a next() method that returns a promise which resolves to an object with value and done properties.
Think of it like a vending machine that takes time to dispense items: instead of getting your snack immediately, you get a ticket (promise) that says "your item is coming." When the promise resolves, you receive an object telling you what you got (value) and whether the machine is empty (done).
The Structure
An async iterator must have:
{
next() {
// Returns a promise that resolves to { value, done }
return Promise.resolve({ value: someValue, done: false });
}
}
The key difference from sync iterators: next() returns a promise that resolves to the result object, not the result object directly.
Why Promises?
Since async iterators deal with data that arrives over time (API calls, file streams, database queries), each next() call might need to wait. The promise lets the consumer know "I'm working on it" and delivers the result when ready.
When done: true is returned, the iteration completes—just like synchronous iterators, but asynchronously.
Key Takeaway: The async iterator protocol requires a next() method that returns a promise resolving to { value, done }, enabling asynchronous iteration over data that arrives over time.