Promises vs Observables in JavaScript

July 29, 2019

Promises & Observables are often seen as a similar concept in JavaScript. This article differentiates the properties of a JavaScript Promise with an Observable.




Promises vs Observables in JavaScript

Native vs Non-Native

A promise in JavaScript is a native feature that was introduced in ECMAScript 6. This is the feature supported by all modern browsers natively without the use of any external library or plugin.
An Observable is not a native feature of JavaScript. It is provided by an external library named RxJS that has complete documentation for its usage. To use an Observable, we must include the RxJS library in the project.

Single-valued vs Multi-valued

A promise can be resolved only once. Once the Promise is resolved, the chained then() method will be called.
An Observable uses an indefinite data-stream. Unlike Promises, it can send multiple values to its subscription. It can be definite or indefinite. For an Observable to be definite, we need to call the complete() from within the observable. If complete() is not called, the subscriber will keep listening to the observable until it is unsubscribed using the unsubscribe() method.

Lazy vs Non-lazy

A Promise is not lazy in nature. A promise will be executed even if there is no then statement chained to that Promise. No matter you chain a promise with a then()catch() or finally(), the promise will execute.
//this will execute the promise
/* delay().then(function(response) {
  alert('Promised!');
}); */
//this will also execute the promise
delay();

//delay function with Promise
function delay() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            alert("Promise is now being resolved");
            resolve('success');
            //reject('error');
        }, 2000);
    });
}
An Observable is lazy in nature i.e. it won’t run until there is a subscription for that observable. If there is no subscription for an observable, the observable will not run.
//this will execute the promise
/* delay().then(function(response) {
  alert('Promised!');
}); */
//this will also execute the promise
delay();

//delay function with Promise
function delay() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            alert("Promise is now being resolved");
            resolve('success');
            //reject('error');
        }, 2000);
    });
}

Cancellable vs Non-Cancellable

A Promise is not cancellable by default. Canceling a Promise is not a native property of a Promise. Though there exist libraries that can be used to cancel a Promise.
An Observable can be canceled without the use of any external library. We can cancel an observable any time by calling the unsubscribe method on its alias.
// Observables push values to their subscribers:
var obs = Rx.Observable.create(function(observer){
  observer.next('Hello');
  observer.next('World');
  setTimeout(function(){
    observer.next('Goodbye');
    if(Math.random()>0.5){
      observer.error(new Error("boo!"));
    } else {
     observer.complete();
    }
  }, 1000);
});

//cancelling an observable
obs.unsubscribe();

//This code won't run as the Observable has been cancelled
// Obsrvable won't execute without the subscribe method chained to it
obs.subscribe(
  function valueHandler(value){
    alert(value);
  },
  function errorHandler(err){
    alert(err);
  },
  function completeHandler(){
    alert('Completed');
  }
);

Sending Data

A promise can use the resolve() method to pass some data to the chained then() function to be operated on that data.
An observable use the next() method to send the next value/data to its subscriber. After all values are sent to the subscriber, the observer uses the complete() method to close the data stream. It is not mandatory for the observable to close the data stream. Instead, we can call the unsubscribe()method on the alias of the observable.

Chaining Methods

A Promise has available options for chaining with then()catch() or finally() method.
An Observable has the options of chaining with many functions like subscribe(the most common chaining method), mapfilterreduceforEach, … and the list is pretty long.

You Might Also Like

0 comments

Follow by Email