Making a promise with javascript

Chaining functions in javascript is fun, so is the understanding of Blaocking 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 pattern!

Promises are not a 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.

Summarising 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 :


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();"GET",URL,true);
  // Register the event handler
    if(xhr.status === 200){
  // Make the XHR call.
  //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!

Share this