Symbol.asyncIterator for Async Iteration
What You'll Learn
You'll learn how to make objects asynchronously iterable so they work seamlessly with for-await-of loops by implementing Symbol.asyncIterator.
The Core Idea
Just as Symbol.iterator makes objects work with regular for-of loops, Symbol.asyncIterator enables objects to work with asynchronous iteration using for-await-of. This is perfect when your data arrives over time—like fetching paginated API results, reading file streams, or processing queued messages.
Think of it like a vending machine: A regular iterator (Symbol.iterator) dispenses items immediately when you press a button. An async iterator (Symbol.asyncIterator) takes your order but tells you "please wait" while it prepares each item—maybe it needs to fetch ingredients or wait for the next batch to arrive.
How It Works
When you implement Symbol.asyncIterator on an object, you return an async iterator—an object whose next() method returns a Promise that resolves to {value, done}:
const asyncRange = {
start: 1,
end: 3,
[Symbol.asyncIterator]() {
let current = this.start;
const end = this.end;
return {
async next() {
// Simulate async delay
await new Promise(resolve => setTimeout(resolve, 500));
if (current <= end) {
return { value: current++, done: false };
}
return { done: true };
}
};
}
};
// Now you can use for-await-of
(async () => {
for await (const num of asyncRange) {
console.log(num); // 1... 2... 3... (with delays)
}
})();
Each call to next() is async, allowing you to fetch data, wait for timers, or perform any asynchronous operation before yielding the next value.
Key Takeaway: Implement Symbol.asyncIterator to make objects work with for-await-of, enabling clean iteration over data that arrives asynchronously through Promises.