refer: promise-vs-observable
先上总结:
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 and allows to pass zero or more events where the callback is called for each event.
Observable 允许 0 or more event,回调函数在每次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比Promise更好,因为它提供了不止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有一个优势:可取消。如果不再需要一个HTTP请求/某些昂贵的异步操作,Observable可以取消订阅,而Promise仍会执行 success/failed 回调函数。
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 Promise handles a single event when an async operation completes or fails.
此外,Observable还提供了很多类数组的操作子,以及更多的高阶操作子。
Promise VS Observable
Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript. They are very similar in many cases, however, there are still some differences between the two as well, promises are values that will resolve in asynchronous ways like http calls. On the other hand, observables deal with sequence of asynchronous events. The main differences are listed as below:
promise:
- having one pipe line
- usually only use with async data return
- not easy to cancel
observable:
- are cancellable
- are retriable by nature such as retry and retryWhen
- stream data in multiple pipe lines
- having array-like operations like map, filter etc
- can be created from other sources like events
- they are function, which could be subscribed later on
Also, I've created the graphical image for you below to show the differences visually: