天天看點

promise和Observables的差別

訂閱專欄

StackOverflow上有一個讨論:What is the difference between Promises and Observables?

一篇有用的部落格:Angular2 Observables, Http, and separating services and components

Angular官網的一篇文章:Observables compared to other techniques

Observable和promise的差別:

Observables are declarative; computation does not start until subscription. Promises execute immediately on creation. This makes observables useful for defining recipes that can be run whenever you need the result.

Observable是陳述式的,計算直至subscription才會觸發。這和promise很不同——promise建立之後,立即執行。

Observables provide many values. Promises provide one. This makes observables useful for getting multiple values over time.

Observable提供多個值,而promises隻能提供單個值。

Observables differentiate between chaining and subscription. Promises only have .then() clauses. This makes observables useful for creating complex transformation recipes to be used by other part of the system, without causing the work to be executed.

Observable可以借助rxjs豐富的Operators,組合成複雜的transformation recipes, 便于應用内的重用,而promise隻有一個then操作。

Observables subscribe() is responsible for handling errors. Promises push errors to the child promises. This makes observables useful for centralized and predictable error handling.