HTML5 Zone is brought to you in partnership with:

A GNU/Linux g33k CLI+Web loving computer polyglot. Hemanth is a DZone MVB and is not an employee of DZone and has posted 16 posts at DZone. You can read more from them at their website. View Full User Profile

Making a Promise with JavaScript

10.31.2012
| 4346 views |
  • submit to reddit

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!

 

 

 

Published at DZone with permission of Hemanth Madhavarao, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)