Promises 和 Observables 有什么区别? [英] What is the difference between Promises and Observables?
问题描述
Angular 中的 Promise
和 Observable
有什么区别?
每个示例都有助于理解这两种情况.我们可以在什么场景下使用每种情况?
承诺
当异步操作完成或失败时,Promise
处理单个事件.
注意:有支持取消的 Promise
库,但 ES6 Promise
到目前为止还没有.
可观察
Observable
就像一个 Stream
(在许多语言中)并且允许传递零个或多个事件,其中为每个事件调用回调活动.
通常 Observable
比 Promise
更受欢迎,因为它提供了 Promise
的特性等等.使用 Observable
处理 0、1 或多个事件并不重要.您可以在每种情况下使用相同的 API.
Observable
还具有优于 Promise
的优势,即可取消.如果不再需要对服务器的 HTTP 请求或其他一些昂贵的异步操作的结果,Observable
的 Subscription
允许取消订阅,而 Promise
最终会调用成功或失败的回调,即使您不再需要通知或它提供的结果.
虽然 Promise
会立即启动,但 Observable
仅在您订阅它时才会启动.这就是为什么 Observable 被称为懒惰的原因.
Observable 提供了操作符,如map
、forEach
、reduce
、...类似于数组>
还有一些强大的运算符,例如 retry()
或 replay()
,...通常非常方便.rxjs 附带的运算符列表
延迟执行允许在通过订阅执行 observable 之前建立一系列操作符,以进行更具声明性的编程.
What is the difference between Promise
and Observable
in Angular?
An example on each would be helpful in understanding both the cases. In what scenario can we use each case?
Promise
A Promise
handles a single event when an async operation completes or fails.
Note: There are Promise
libraries out there that support cancellation, but ES6 Promise
doesn't so far.
Observable
An Observable
is like a Stream
(in many languages) and allows to pass zero or more events where the callback is called for each event.
Often Observable
is preferred over Promise
because it provides the features of Promise
and more. With Observable
it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.
Observable
also has the advantage over Promise
to be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription
of an Observable
allows to cancel the subscription, while a Promise
will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.
While a Promise
starts immediately, an Observable
only starts if you subscribe to it. This is why Observables are called lazy.
Observable provides operators like map
, forEach
, reduce
, ... similar to an array
There are also powerful operators like retry()
, or replay()
, ... that are often quite handy.
A list of operators shipped with rxjs
Lazy execution allows to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.
这篇关于Promises 和 Observables 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!