What are the core differences between Observables and Promises

A Promise handles asingle eventwhen an async operation completes or fails.

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

An Observable is like aStream(in many languages) and allows to pass zero or more events where the callback is called for each 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 also has the advantage over Promise to becancelable. 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 providesoperatorslike map, forEach, reduce, ... similar to an array. There are also powerful operators like retry(), or replay(), ... that are often quite handy.

Promises vs Observables

  • Promises:
    1. returns a single value
    2. not cancellable
  • Observables:

  • works with multiple values over time

  • cancellable

  • supports map, filter, reduce and similar operators

  • proposed feature for ES 2016
  • use Reactive Extensions (RxJS)
  • an array whose items arrive asynchronously over time

results matching ""

    No results matching ""