Creating a Custom Async Iterable
You'll learn how to implement Symbol.asyncIterator on your own object to make it async-iterable with asynchronously-resolved values.
The Core Idea
Just as Symbol.iterator makes an object iterable in for...of loops, Symbol.asyncIterator makes an object async-iterable in for await...of loops. You define a method that returns an async iterator—an object with a next() method that returns promises resolving to { value, done } objects.
Think of it like creating a custom streaming playlist: instead of loading all songs at once, each song loads asynchronously as you request it.
Building Your Own Async Iterable
const asyncRange = {
start: 1,
end: 3,
delay: 500,
[Symbol.asyncIterator]() {
let current = this.start;
const end = this.end;
const delay = this.delay;
return {
async next() {
if (current <= end) {
// Simulate async operation
await new Promise(resolve => setTimeout(resolve, delay));
return { value: current++, done: false };
}
return { done: true };
}
};
}
};
// Use it with for await...of
(async () => {
for await (const num of asyncRange) {
console.log(num); // 1... 2... 3... (each after 500ms delay)
}
})();
Notice how Symbol.asyncIterator returns an object with an async next() method. Each call to next() returns a promise that resolves to the iterator result object, allowing values to be produced asynchronously.
Why This Matters
This pattern lets you represent sequences of data that arrive over time—database query results, paginated API responses, or sensor readings—as naturally iterable objects.
Key Takeaway: Implementing Symbol.asyncIterator on an object makes it async-iterable, letting you use for await...of loops to consume values that resolve asynchronously through the async iterator protocol.