Over a million developers have joined DZone.
Platinum Partner

Making a Promise with JavaScript

· Web Dev Zone

The Web Dev Zone is brought to you in partnership with Mendix. Download this Forrester Report to gain a better understanding of the low-code platform market and how to make a strategic platform selection you won’t regret.

Chaining functions in javascript is fun, so is the understanding of Blocking vs Non-Blocking code, but callback can soon end up in hell!

To save one from callback hell, normally named functions are preferred as save boats, but promises are more promising patterns!

Promises are not new to the world of computer science, many JS frameworks have made promises for quite some time now, jQuery Deffered being one amongst them, taskjs is also very impressive.

Summarizing the promise in simple points :

  • An object that represents a one-time event, typically the outcome of an async task.

  • That function must return a promise, which can be fulfilled with a value or failed with an exception!

  • State transitions are performed based on the promises outcome.

  • Once the transition is done, it's state is frozen.

But normally there are more methods in it like :

.done()
.fail()
.then()
.when()
.progress() 
.isResolved()
.isRejected()
.always()
.pipe()
.state()

Simple example :

var Promise = function() {} // Empty Promise ;)  
 
Promise.prototype.then = function (resolved, rejected) {
// Do a state transition, based on the result 
};
 
Promise.prototype.resolve = function (value) {
// Transit to resolved
};
 
Promise.prototype.reject = function (error) {
// Transit to rejected
};

Now we can make promises with a async block of code, like :

function doXHR(URL){
  //Mkae a promise 
  var promise = new Promise();
  var xhr = new XMLHttpRequest();
  xhr.open("GET",URL,true);
 
  // Register the event handler
  xhr.addEventListener('load',function(){
    if(xhr.status === 200){
      promise.resolve("Done");
    }
    else{
      promise.reject("Failed");
    }
  },false) 
 
  // Make the XHR call.
  xhr.send();
 
  //Return the promise
  return promise;
}

We can now use the thus defined, function like :

doXHR(URL).then(function (data) {
  // Play with the data
});

Start making your promises!

 

 

 

The Web Dev Zone is brought to you in partnership with Mendix. Better understand the aPaaS landscape and how the right platform can accelerate your software delivery cadence and capacity with the Gartner 2015 Magic Quadrant for Enterprise Application Platform as a Service.

Topics:

Published at DZone with permission of Hemanth HM , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}