Promise in Javascript with example

If you are wondering what is promise in Javascript then you are in the perfect place. A promise in Javascript is another way to write asynchronous code in a more synchronous fashion.

In the last article, we discussed the callbacks in javascript and we all know that it does the same job i.e to allow us to write asynchronous code in a synchronous manner.

So why do we need Promises in Javascript and what are its benefits over callbacks, this article is all about these questions. So without wasting more time let’s dive in.

Promise in Javascript

What is Promise in Javascript?

A promise is an object which represents the result of an asynchronous operation which is either resolved or rejected. A Promise in Javascript can have 3 states which are as follows:

  1. Fulfilled: onFulfilled() will be called (e.g., resolve() was called)
  2. Rejected: onRejected() will be called (e.g., reject() was called)
  3. Pending: not yet fulfilled or rejected

Here is a simple example of Promise in Javascript

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
  }, 300);

promise1.then(function(value) {
  // expected output: "foo"

// expected output: [object Promise]

How Promise works in Javascript?

A Promise allows us to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods.

Instead of immediately returning the final value, the asynchronous method returns a promise to supply the value whenever the assigned task gets completed in the future.

promises in javascript
Promise in Javascript

Why there is a need for Promise over Callbacks?

At this point, we know that Promise in Javascript does the same things which callbacks are doing. So, what’s the need for promises. Let’s know

In a long web application, or in a big program the extensive use of callbacks can create a condition that is widely known as Callback Hell. We all know that a callback is a block of code passed an argument to a function, which can be executed by the function at a suitable time.

There is nothing wrong with callbacks, but when you have conditions where you have multiple callbacks nested within each other, it becomes very messy.

Here is an example of callback hell

function getRestaurants(){
                        coordinates: position 
                }, function(restaurants){
      console.log("Unable to process request")
  }, function(){
    console.log("Unable to process request")

To avoid this problem i.e Callback Hell, Promises are introduced in Javascript which is more easier to use and work with.

Leave a Comment