What Are JavaScript Promises

Posted By : Mahima Gautam | 18-Aug-2018

What exactly the promises in javascript are -: It is an object that represents the eventual completion or failure of the asynchronous operation. However, it is a returned object that we attach to our callbacks, instead of passing callbacks it into a function.

 

What are the advantages of using javascript promises

  • Better definition to the control flow of asynchronous logic.
  • Reduced coupling.
  • Better error handling
  • Improved readability

 

How promises work in javascript?

 

First, we will talk for javascript concurrency. It is single threaded and everything that happens in a line by line sequence. But asynchronous call operations occur in order the gets complete.

In the following example what will be the output on a console

 

console.log("1");
setTimeout(function(){console.log("2");},3000);
console.log("3");
setTimeout(function(){console.log("4");},1000);

 

The above code output will be like 1, 3, 4, 2. As we can see why 4 is printed before 2. The reason behind it is, even though line 2 started its execution before the line  number 4, but it did not start the execution for 3000ms and therefore 4 is logged before 2

 

In the complex and typical web-applications, we make n number of asynchronous call operations, like getting images, fetching data from the JSON endpoints, communicating with APIs etc.

 

Let's see how can we make promises in the javascript. Following is the example:- 

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

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

 

In the above example, the constructor with the name promise takes one argument: as a callback function with the two parameters that are resolved and reject. Now we can use this promise as follows: 

 

promise.then(function(result) {
  console.log("Promise worked");
}, function(err) {
  console.log("Something broke");
});

 

Now if the above promise code is successful, a resolved case will happen and on the console will see the result "Promise worked", otherwise "something broke" That is a state of in-between of resolve and reject where we haven't received the response that will be considered as pending state. So to conclude there are 3 states to promise

 

  • Pending: Awaiting promise response
  • Resolve: Promise has successfully returned
  • Reject: Failure occurred

 

Promise: Example

To understand the full concept behind the promise, let's make an app where we will load the image. When the image gets loaded, will display the image, else will print the error.

 

Create promise via using XMLHttpRequest(XHR)

 

const loadImage = url => {
  return new Promise(function(resolve, reject) {

    //Open a new XHR
    var request = new XMLHttpRequest();
    request.open('GET', url);

    // When the request loads, check whether it was successful
    request.onload = function() {
      if (request.status === 200) {
        // If successful, resolve the promise
        resolve(request.response);
      } else {
        // Otherwise, reject the promise
        reject(Error('An error occurred while loading image. error code:' + request.statusText));
      }
    };

    request.send();
  });

};

In above example when the image loads successfully, the promise will be gone in resolve state with the response coming from XHR. Now let's move further and use the promise by calling a loadImage function

 

const embedImage = url => {
  loadImage(url).then(function(result) {
      const img = new Image();
      var imageURL = window.URL.createObjectURL(result);
      img.src = imageURL;
      document.querySelector('body').appendChild(img);
    },
    function(err) {
      console.log(err);
    });
}

the above example image will be loaded. 

 

In the end, will conclude that in most scenarios these promises can be proved really helpful especially in the case where success and failure callbacks are called only once. But exceptions are always there, in some cases simple callbacks are proved to be better when the callback needs to be fired multiple times.

About Author

Author Image
Mahima Gautam

Mahima has a good knowledge of HTML and CSS. She is working as a UI Developer and she loves to dance in her free time.

Request for Proposal

Name is required

Comment is required

Sending message..