Difference between Promises and Observables

September 17, 2022 No comments promis observables angular difference js

Promis


  • Handles a single event when an async operation completes or fails,
  • Doesn't support cancellation,
  • Promise will eventually call the success or failed callback even when you don't need the notification or the result it produces,
  • Promise starts immediately,
  • Does not provide any operators.

Example #1:

 var promise = new Promise((resolve, reject) => {
  // do something once, possibly async
  // code inside the Promise constructor callback is getting executed synchronously

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//usage
promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);

Example #2:

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("Hello from a Promise!");
  }, 2000);
});

promise.then(value => console.log(value))

Observable

  • Similar to a stream, an observable permits the passing of zero or more events, with the callback being triggered by each event,
  • Observable allows you to handle 0 events, 1 events, or numerous events,
  • The subscription of an Observable allows you to cancel the subscription if the result of an HTTP request to a server or some other expensive async operation is no longer required,
  • Observable doesn't begin until you subscribe to it, Observables are said to as lazy,
  • Similar to an array, Observable offers operators like map, forEach, reduce, etc.,
  • Before the observable is processed via subscribing, a chain of operators may be built up using lazy execution, allowing for more declarative programming,
  • Can be created from other sources like events.

Example #1:
    
const observable = Rx.Observable.create(observer => {
  // create a single value and complete
  observer.onNext(1);
  observer.onCompleted();
});

source.subscribe(
  x => console.log('onNext: %s', x),   //  success callback
  e => console.log('onError: %s', e),  //  error callback
  () => console.log('onCompleted')     //  completion callback
 );

// first we log: onNext: 1
//  then we log: onCompleted

Example #2:

const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from a Observable!');
  }, 2000);
});

observable.subscribe(value => console.log(value));
{{ message }}

{{ 'Comments are closed.' | trans }}