Promises和Observables有什么区别? [英] What is the difference between Promises and Observables?

查看:146
本文介绍了Promises和Observables有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PromiseObservable在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.

通常ObservablePromise更受青睐,因为它提供了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请求或其他昂贵的异步操作的结果,则ObservableSubscription允许取消订阅,而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提供操作符,例如mapforEachreduce,...,类似于数组

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屋!

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