The async iterable protocol
An async iterable implements [Symbol.asyncIterator]() returning an object whose next() method returns a **Promise** that resolves to { value, done }. for await...of calls this automatically.
// Manual async iterable
const asyncRange = {
from: 1,
to: 3,
[Symbol.asyncIterator]() {
let current = this.from
const last = this.to
return {
async next() {
await new Promise(r => setTimeout(r, 100)) // simulate async
return current <= last
? { value: current++, done: false }
: { value: undefined, done: true }
}
}
}
}
for await (const n of asyncRange) {
console.log(n) // 1, 2, 3 (100ms apart)
}