Basics
suggest changeA JavaScript iterator is an object with a .next() method. That method returns an iterator result: an object with value and done.
An async iterator's .next() method returns a promise for that result.
To create an AsyncIterator, we can use the async generator syntax:
/**
* Returns a promise that resolves after `time` milliseconds.
*/
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;
}
}
delayedRange takes a maximum and returns an async iterator. It yields the integers from 0 up to, but not including, that maximum, one second apart.
Usage:
for await (let number of delayedRange(10)) {
console.log(number);
}
for await...of is allowed in async functions and at the top level of a module. The generator yields numbers, not promises. The loop awaits each call to next() for you, so number is the fulfilled value.
The example waits one second, logs 0, waits another second, logs 1, and so on, until it logs 9. The iterator is then done and the loop exits. for await...of outside an async function or module is a syntax error.