异步迭代器的实现主要依赖ES6的常用内置符号(well-known symbol)->Symbol.asyncIterator.在类里创建构造器和生成器。在异步函数中调用并使用await 来产生异步迭代行为
代码如下:
class Emitter {
constructor(max){
this.max = max;
this.index = 0;
}
async *[Symbol.asyncIterator] (){
while(this.index<this.max)
yield new Promise((resolve)=>resolve(this.index++));
}
}
async function generator(){
let emitter = new Emitter(5);
for await (const x of emitter)
console.log(x);
}
generator();