Brief Introduction To Promises in ES6

Posted By : Avilash Choudhary | 29-Jun-2017

Hi Guys,

Today we are discussing promises which are introduced in es6, they provide better replacement for callbacks in javascript. Callback are sometimes really confusing when used nestedly. Promises are better approach for async javascipt operations. Promises provide resolve and reject methods. resolve stands for success and reject stands for failure.

Promises also return something whether success or failure. When promise is returned by a method this is handled in a then function. Lets create a simple example for promises.

function display(){ 
var a = new Promise(function(resolve,reject){ 

setTimeout(function(){ 

resolve(); 

},500);

}); 

}


 display.then(function(success){ 
// do something in success 
},function(error){ 
// do something in failure
}); 
 

Always handle promises success and failure callbacks, because when you have rejected the promises it will go to the error callback and if it is not present it will throw the error to the console. You can use promises then chaining. Promises are best for asynchronous programming, when you send a call to server then you to wait for couple of seconds to get response from server. In that case, if there is success with network , you get resolve promise, in case of failure you got reject promise. 

There are several methods with promises, like Promise.all() returns a promise which fulfills when all promises fulfilled in iterable argument and returns rejects if one of the promises in the iterable argument rejects.

Promises in ajax call:

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do anything here
    var request = new XMLHttpRequest();
    request.open('GET', url);

    request.onload = function() {
      // check the status here
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(request.response);
      }
      else {
        // Otherwise reject with the status text
        reject(Error(request.statusText));
      }
    };

    // Handle network errors
    request.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request to network
    request.send();
  });
}

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..