Async Iterators with Delayed Values
You'll learn how to build async iterators that simulate streaming data by introducing deliberate delays between yielded values.
The Core Idea
Real-world data streams—like sensor readings, API pagination, or live feeds—don't deliver all values instantly. By combining async iterators with setTimeout or promise-based delays, you can model this behavior: your iterator pauses between values, simulating network latency or timed events.
This technique transforms your async iterator from a simple sequential data source into something that behaves like actual streaming data arriving over time.
How It Works
Inside your async iterator's next() method, introduce a delay before resolving with the next value. You can wrap setTimeout in a promise or use any async operation:
const delayedRange = {
[Symbol.asyncIterator]() {
let current = 1;
return {
async next() {
if (current > 3) {
return { done: true };
}
// Simulate delay (e.g., 1 second)
await new Promise(resolve => setTimeout(resolve, 1000));
return { value: current++, done: false };
}
};
}
};
(async () => {
for await (const num of delayedRange) {
console.log(num); // Logs 1... (wait 1s) ...2... (wait 1s) ...3
}
})();
Each iteration waits for the promise to resolve before yielding the next value. The consumer naturally pauses at each await, creating a time-spaced stream.
Why This Matters
This pattern is essential for testing async code, simulating API throttling, or building educational demos of streaming behavior without actual network calls.
Key Takeaway: By adding await delays inside an async iterator's next() method, you create time-spaced value streams that accurately model real-world asynchronous data sources.