Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

angular - Promises和Observables有什么区别?(What is the difference between Promises and Observables?)

Can someone please explain the difference between Promise and Observable in Angular?

(有人可以解释Angular中PromiseObservable之间的区别吗?)

An example on each would be helpful in understanding both the cases.

(每个示例都将有助于理解这两种情况。)

In what scenario can we use each case?

(在什么情况下我们可以使用每种情况?)

  ask by Rohit translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Promise

(诺言)

A Promise handles a single event when an async operation completes or fails.

(当异步操作完成或失败时, Promise处理一个事件 。)

Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

(注意:那里有支持取消的Promise库,但是ES6 Promise到目前为止还不支持。)

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.

(一个Observable就像一个Stream (在许多语言中),并且允许传递零个或多个事件,其中每个事件都被调用回调。)

Often Observable is preferred over Promise because it provides the features of Promise and more.

(通常, ObservablePromise更为可取,因为它提供了Promise等功能。)

With Observable it doesn't matter if you want to handle 0, 1, or multiple events.

(使用Observable ,您要处理0、1或多个事件都没有关系。)

You can utilize the same API in each case.

(在每种情况下,您都可以使用相同的API。)

Observable also has the advantage over Promise to be cancelable .

(与Promise相比, Observable也具有可取消的优势。)

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.

(如果不再需要对服务器的HTTP请求或其他昂贵的异步操作的结果,则ObservableSubscription可以取消该预订,而Promise最终将调用成功或失败的回调,即使您不需要需要通知或它提供的结果了。)

Observable provides operators like map , forEach , reduce , ... similar to an array

(Observable提供类似于数组的mapforEachreduce ,...等运算符)

There are also powerful operators like retry() , or replay() , ... that are often quite handy.

(还有一些功能强大的运算符,例如retry()replay() ……通常非常方便。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...