Question 29
Question
Answer
class InfiniteAsyncIterator {
constructor() {
this[Symbol.asyncIterator] = this.asyncIterator.bind(this);
}
async* asyncIterator() {
let count = 0;
while (true) {
yield `Value ${count++}`;
await new Promise(resolve => setTimeout(resolve, 100)); // Simulate an async operation
}
}
}
const iterator = new InfiniteAsyncIterator();
async function consumeIterator() {
for await (const value of iterator) {
console.log(value);
// Do something with the yielded value...
if (count > 10) break; // Stop after a certain number of values
}
}
consumeIterator(); Last updated