Promises和Observables有什么区别? [英] What is the difference between Promises and Observables?
问题描述
Promise
和Observable
在Angular中有什么区别?
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.
注意:那里有Promise
个库支持取消功能,但是ES6 Promise
到目前为止还不行.
Note: There are Promise
libraries out there that support cancellation, but ES6 Promise
doesn't so far.
可观察
Observable
就像 Stream
(在许多语言中一样),并允许传递零个或多个事件,其中每个事件都需要回调.
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.
通常Observable
比Promise
更受青睐,因为它提供了Promise
及更多功能.使用Observable
并不需要处理0、1或多个事件.在每种情况下,您都可以使用相同的API.
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
还具有可取消的优势.如果不再需要对服务器的HTTP请求或其他昂贵的异步操作的结果,则Observable
的Subscription
允许取消订阅,而Promise
最终将调用成功或失败的回调即使您不再需要通知或通知所提供的结果.
Observable
also has the advantage over Promise
to be cancelable. 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.
Observable提供操作符,例如map
,forEach
,reduce
,...,类似于数组
Observable provides operators like map
, forEach
, reduce
, ... similar to an array
还有一些功能强大的运算符,例如retry()
或replay()
,...常常非常方便.
There are also powerful operators like retry()
, or replay()
, ... that are often quite handy.
这篇关于Promises和Observables有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!