Page 137 - JavaScript
P. 137
* Returns a promise which resolves after time had passed.
*/
const delay = time => new Promise(resolve => setTimeout(resolve, time));
async function* delayedRange(max) {
for (let i = 0; i < max; i++) {
await delay(1000);
yield i;
}
}
The delayedRange function will take a maximum number, and returns an AsyncIterator, which yields
numbers from 0 to that number, in 1 second intervals.
Usage:
for await (let number of delayedRange(10)) {
console.log(number);
}
The for await of loop is another piece of new syntax, available only inside of async functions, as
well as async generators. Inside the loop, the values yielded (which, remember, are Promises) are
unwrapped, so the Promise is hidden away. Within the loop, you can deal with the direct values
(the yielded numbers), the for await of loop will wait for the Promises on your behalf.
The above example will wait 1 second, log 0, wait another second, log 1, and so on, until it logs 9.
At which point the AsyncIterator will be done, and the for await of loop will exit.
Read Async Iterators online: https://riptutorial.com/javascript/topic/5807/async-iterators
https://riptutorial.com/ 94

