何时使用 Promise 而不是 observable? [英] When to use Promise over observable?

查看:29
本文介绍了何时使用 Promise 而不是 observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有比 observable 更强大的 Promise 的情况?我知道 observables 比 promises 有很多好处.但是有没有什么情况,我应该只使用 observables 上的承诺.

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.

我找到了这个链接,promises vs observables.但这总是向我展示了 observables 比 promises 的好处.我想知道 promise 相对于 observable 的好处.

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.

推荐答案

一个 observable 能做 Promise 能做的所有事情,甚至更多.如果需要承诺,它总是可以通过 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

  • 相关问题中详细解释了observables固有的任何功能而不是promise需求(特别是取消订阅、不完整的 observable 和接收多个值的 observable)
  • 使用它的 API 需要一个 observable 并且不使用 Observable.from(...) 安全结构来统一 observable 和 promise
  • 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

如果使用 observable 的代码只使用 observable,则可以选择它而不是 promise.

An observable may be chosen over a promise if the code where it's used uses observables exclusively.

如果使用 observable 的 API 期望承诺并且不使用 Observable.from(...) 安全结构,则承诺必须被选择而不是 observable.

A promise must be chosen over an observable if API that consumes it expects a promise and doesn't use Observable.from(...) safety structure.

一个承诺可能被选择而不是一个可观察的如果

A promise may be chosen over an observable if

  • 使用它的代码专门使用 promises(特别是 async 函数)
  • 设计上需要异步
  • 它需要立即订阅和链接然后,因为一个链应该在 observables 中被打破 let observable = ...;observable.subscribe(...);返回 observable (这还需要跟踪多个订阅,以防 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 而不是 observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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