问题描述
我希望能够等待一个可观察的对象,例如
I'd like to be able to await on an observable, e.g.
const source = Rx.Observable.create(/* ... */)
//...
await source;
天真的尝试导致等待立即解决而不是阻止执行
A naive attempt results in the await resolving immediately and not blocking execution
我的完整预期用例的伪代码是:
The pseudocode for my full intended use case is:
if (condition) {
await observable;
}
// a bunch of other code
我知道我可以将其他代码移到另一个单独的函数中并将其传递给订阅回调,但我希望能够避免这种情况.
I understand that I can move the other code into another separate function and pass it into the subscribe callback, but I'm hoping to be able to avoid that.
推荐答案
您必须将承诺传递给 await
.将 observable 的下一个事件转换为 promise 并等待它.
You have to pass a promise to await
. Convert the observable's next event to a promise and await that.
if (condition) {
await observable.first().toPromise();
}
编辑注意:此答案最初使用 .take(1) 但已更改为使用 .first() 避免了如果流在值通过之前结束则无法解决 Promise 的问题.
从 RxJS v8 开始,toPromise
将被移除.相反,上述内容可以替换为 await firstValueFrom(observable)
As of RxJS v8, toPromise
will be removed. Instead, the above can be replaced with await firstValueFrom(observable)
这篇关于我如何在 Rx Observable 上“等待"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论