Promises and Observables - JavaScript

Sandali Tharuki
Nerd For Tech
Published in
2 min readMay 23, 2021

--

Courtesy: Beautiful Free Images & Pictures | Unsplash

We can use Promises and observables with Asynchronous in JavaScript. Both the approaches look the same but have differences.

Promises

In promises, the function returns a promise. A task is assigned to the promise to perform after the Async completes. Async and Await are keywords more often come with Promise. The Await keyword delays the execution of the Async function until the promise performs the task which is assigned with. Promise passes three states during its execution cycle.

  • Pending

The word, Pending conveys the meaning of “Not yet stared”. This is the initial state of the Promise.

  • Fulfilled

The word, Fulfilled has the meaning of “Completed”. In this stage, the task which is assigned to Promise was completed.

  • Rejected

The word, Rejected means the task is “Denied”. In this stage, the task was not completed and an error was thrown.

We can use Promises when we are dealing with a single async operation.

Observables

Observables can be used when we need to handle a sequence of data over time. Observables take place when the next event occurs, when an error occurs and when the task is completed. A callback function is used with Observables to supply an argument to the Observable. The three available callbacks are,

  • onNext
  • onCompleted
  • onError

Observables pass Four stages,

  • Creation

An observable is initiated in this stage and we can use create function to initiate an observable.

  • Subscription

We have to subscribe to an observable to make it work. Here we use the subscribe method.

  • Execution

Execution of an observable is the inside of a block.

  • Destruction

Destruction is the stage where an error occurs or observable completes. Though sometimes we have to manually unsubscribe it, most of the time after the destruction of an observable, it is automatically unsubscribed.

Observables vs Promises

  1. Observables are lazy when it is compared to the Promises. Subscriber function is only called when the observable get subscribed. But just after a promise is created, the executor function is called.
  2. Observables can deliver multiple values whereas promises deliver a single value.
  3. After initiating a promise, we can not cancel it. But we can cancel an observable after it is initiated, by simply unsubscribing it.
  4. The promise is always asynchronous and we can only use Async/Await keywords. But the observables can be either asynchronous or synchronous.

I hope this article would be helpful to understand Promises and Observables. You will be able to figure out what are the differences they have.

Thank You!!!

--

--

Sandali Tharuki
Nerd For Tech

Undergraduate-Faculty of Information Technology | University of Moratuwa | Sri Lanka