如何在Rx Observable上“等待”? [英] How can I `await` on an Rx Observable?

查看:346
本文介绍了如何在Rx Observable上“等待”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够等待一个可观察的,例如

I'd like to be able to await on an observable, e.g.

const source = Rx.Observable.create(/* ... */)
//...
await source;

天真的尝试会导致await立即解决并且不会阻止执行

A naive attempt results in the await resolving immediately and not blocking execution

编辑:
我的完整用途用例的伪代码是:

The pseudocode for my full intended usecase is:

if (condition) {
  await observable;
}
// a bunch of other code

我明白我可以将其他代码移动到另一个单独的函数并将其传递给subscribe回调,但我希望能够避免这种情况。

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.

推荐答案

您必须将承诺传递给等待。将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永远不会解决的问题。

这篇关于如何在Rx Observable上“等待”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆