async generators
I have come across generators in javascript before. However, discovered today was a subspecies of async generators. The following is an example of a generator and then using a for loop to print the numbers:
function * getNumbers() {
let count = 0;
do {
yield count;
count++
} while (true);
}
for (const number of getNumbers()) {
console.log(`Number is ${number}`);
}
However, what if the getNumber function was a promise, how could we loop over that? The following code would be invalid:
async function _slowThing(offset) {
return new Promise(resolve => {
setTimeout(() => resolve(true), 5000);
});
}
async function * getNumbers() {
let count = 0;
do {
await _slowThing();
yield count;
count++;
} while (true);
}
(async() => {
for (const number of getNumbers()) {
console.log(`Number is ${number}`);
}
})();
The problem would be the for loop. To fix this, we would change that to be: for await (const number of getNumbers())