[英]Wait for an async operation inside asyncIterator generator function
I have this Queue
class (not the real implementation, but it exemplifies my point):我有这个Queue
class (不是真正的实现,但它体现了我的观点):
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);
}
}
It's just a wrapper for a Javascript Array
with the exception that its methods return a Promise
.它只是 Javascript Array
的包装器,但其方法返回Promise
。
What I want to do is to yield conditionally based on the return value of the pop()
method, which I cannot do because await
is not a valid operation inside an asyncIterator
generator function.我想做的是根据pop()
方法的返回值有条件地产生,我不能这样做,因为await
不是asyncIterator
生成器 function 中的有效操作。
I thought about having a flag which is set in the previous iteration:我考虑过在上一次迭代中设置一个标志:
*[Symbol.asyncIterator]() {
let continue = true;
do {
yield this.pop().then(v => {
if (!v) continue = false;
return v
});
} while (continue);
}
But this would still return a undefined
value in the last execution of pop()
.但这仍然会在pop()
的最后一次执行中返回一个undefined
的值。
I could handle this in the calling code by checking for a undefined
value as a signal of the end of the iteration, but I was wondering if there was a better approach at tackling this problem.我可以在调用代码中通过检查undefined
的值作为迭代结束的信号来处理这个问题,但我想知道是否有更好的方法来解决这个问题。
You can use an async
generator function (MDN docs missing, but see eg this article ) for the implementation of the [Symbol.asyncIterator]()
method :您可以使用async
生成器 function (缺少 MDN 文档,但请参阅例如 这篇文章)来实现[Symbol.asyncIterator]()
方法:
async *[Symbol.asyncIterator]() { /*
^^^^^ */
while (this._arr.length) {
yield await this.pop(); // no longer a problem
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.