Question 30
Question
Answer
function* asyncGenerator() {
yield 1; // Yield the first value
await new Promise(resolve => setTimeout(resolve, 500)); // Simulate async delay
yield 'Hello!';
yield 2;
yield await new Promise(resolve => setTimeout(() => resolve(3), 300));
}
// Create an asynchronous iterable object using Symbol.asyncIterator
const iterable = {
[Symbol.asyncIterator]: asyncGenerator.bind() // Bind the generator function to the context of 'this'
};
async function consumeIterable() {
for await (const value of iterable) {
console.log(value);
}
}
consumeIterable(); // Run the async function to iterate over the valuesLast updated