我有这个Queue
类(不是真正的实现,但它体现了我的观点):
class Queue {
constructor() {
this._arr = [];
}
async push(elem) {
this._arr.push(elem);
}
async pop() {
return this._arr.pop();
}
*[Symbol.asyncIterator]() {
do {
let res = await this.pop(); // here is the problem
if (res) yield res;
} while (res);
}
}
它只是 Javascript 的包装器,只是Array
它的方法返回一个Promise
.
我想要做的是根据pop()
方法的返回值有条件地产生,我不能这样做,因为它不是生成器函数await
内部的有效操作。asyncIterator
我考虑过在上一次迭代中设置一个标志:
*[Symbol.asyncIterator]() {
let continue = true;
do {
yield this.pop().then(v => {
if (!v) continue = false;
return v
});
} while (continue);
}
但这仍然会undefined
在最后一次执行时返回一个值pop()
。
我可以在调用代码中通过检查一个undefined
值作为迭代结束的信号来处理这个问题,但我想知道是否有更好的方法来解决这个问题。