何时使用Promise over Observable? [英] When to use Promise over observable?
问题描述
在任何情况下,Promise都比可观察的功能更强大吗?我知道可观察到的东西比诺言有很多好处.但是,无论如何,我应该只对可观察对象使用promise.
Is there any case, where Promise is more powerful as compare to observable? I know a lot of benefits of observables over promises. But Is there any case, I should use only promises over observables.
我找到了此链接,承诺与可观察对象.但这始终向我展示了可观察性胜于承诺的好处.我想知道承诺比可观察的好处.
I found this link, promises vs observables. But this always shows me the benefits of observables over promises. I want to know the benefits of promise over observables.
推荐答案
一个可观察者可以做诺言所能做的一切.始终可以使用toPromise()
方法将其切换为诺言,以防出现诺言.
An observable does everything that a promise does and more. It can always be switched to a promise with toPromise()
method in case a promise is expected.
如果可以的话,必须选择一个可观察的
An observable must be chosen over a promise if
- 可观察物固有的但不是承诺的任何特征,并且在相关问题中有详细说明需求(特别是取消订阅,不完整的可观测值和接收多个值的可观测值) 消耗它的
- API期望可观察到的,并且不使用
Observable.from(...)
安全结构来统一可观察到的事物和诺言
- any features that are intrinsic to observables and not promises and explained in detail in related question is in demand (notably unsubscription, incomplete observables and observables that receive multiple values)
- API that consumes it expects an observable and doesn't use
Observable.from(...)
safety structure to unify observables and promises
如果使用的代码专门使用可观察对象,则可以在promise上选择可观察的 .
An observable may be chosen over a promise if the code where it's used uses observables exclusively.
一个承诺 .
如果可观察的话,可能会选择一个
A promise may be chosen over an observable if
- 使用其代码的代码专门使用promises(特别是
async
函数) - 它必须在设计上是异步的
- 它必须立即订阅并链接然后,因为在可观察对象
let observable = ...; observable.subscribe(...); return observable
中应该断开一条链(这也需要跟踪多个订阅,以防可观察对象可取消)
- the code where it's used uses promises exclusively (notably
async
functions) - it needs to be asynchronous by design
- it needs to be immediately subscribed and chained then, because a chain should be broken in observables
let observable = ...; observable.subscribe(...); return observable
(this also requires multiple subscriptions to be tracked in case an observable is cancellable)
这篇关于何时使用Promise over Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!