• We Code
  • We Design
  • We Develope
  • We Write
  • We Share

menu

Sunday, July 20, 2014

Promises in JavaScript: What are they and How to use them?

Asynchrony is unavoidable in any platform these days. Asynchrony doesn’t just help the servers to serve their clients better but it also maximizes effective utilization of the resources. JavaScript is no exception.
In recent times, use of asynchronous programming became very important as the expectations out of the software systems that we are writing is went up drastically. And even some of the browser APIs like Indexed DB work on an asynchronous model.
Traditional way of handling asynchronous tasks is the callback model. As the asynchronous tasks are handled by a separate thread or a separate process in some cases, the main program using the asynchronous task doesn’t know when the operation is going to be finished. So, we attach a callback function to the asynchronous task and the attached method would be called when the task is done.Though this approach looks good for upto a chain of one or two asynchronous tasks, it makes the code less readable when we have 3 or more async operations that depend on the result of the previous
operation. Following is an example of such scenario:

Promises: What are they and How to use them?

firstAsyncOperation.onOperationCompleted = function(

if(operationObject.state == “success”){

var secondAsyncOperation = secondAsyncFunction(operation.resultData);

  secondAsyncOperation.onOperationCompleted = function(){

   if(secondAsyncOperation.state == “success”){

     var thirdAsyncOperation = thirdAsyncOperation();

      thirdAsyncOperation.onOperationCompleted = function(){

       if(thirdAsyncOperation.state == “success”){


       }


      };


    }

      };

}else {

//May be some other async operation to handle error case
}

};
That might look beautiful with nice switch between the curly braces and parentheses, but it becomes difficult to manage such code blocks. It becomes really painful when you have to write such blocks multiple times in your code. Promise is a pattern created to solve this issue. Rest of the article speaks about the pattern of promises and how to use them to address this kind of issue.

What is Promise ?
A promise is an object that holds an asynchronous operation. At any given point of time, the object is in one of the three states:

• Pending: When the asynchronous operation is still going on

• Success: When the async operation is successfully completed

• Failed: When the async operation is completed but failed

The promise specification doesn’t tell how to implement a promise, but it says what should be implemented. According to the specification, any promise implementation should have a then callback that accepts two callbacks: one for success and the other for failure. Some implementations (such as Q) also accept a third callback that is invoked when the operation is in progress.

A typical asynchronous operation handled by a Q promise looks like:



asyncOperationObject.then(successCallback, errorCallback, inProgressCallback);

function successCallback(data){
     //----------
     //----------

     //---------- 

    }

function failureCallback(error){

 //----------
 //----------
 //---------- 

 }


 function inProgressCallback(info){

 //----------
 //----------

 //---------- 
 }

 

In general, we pass in anonymous functions as callbacks to the then method. The syntax is shown below:




asyncOperationObject.then(function (data){
//--------
//--------
}, function (error){
//----------
//----------

}, function (info){
//----------
//----------

});


One can include or ignore the callbacks depending upon the need. In most of the scenarios, we ignore the in-progress callback. It can be used to show when there is a need to show a progress bar to indicate the current state.

Chaining Promises

The very first thing we saw in this article is, how dangerous the callback model is for chaining async operations. The best part about the promises is that, the then method also returns a promise object.
This means, we can return another then on the return object.




asyncOperationObject.then(function(data){

   return data;

  }, function(error){

    console.log(error);

  })

  .then(function(data){

    return data

  }, function(error){

    console.log(error);

  })

  .then(function(data){

   return data;

  }, function(error){

   console.log(error);

  });


Though the above operation is chained,it still looks flat. It is very easy to manage such operations as well. More than everything, it is easy to read the subsequent then blocks.

Conclusion:
Understanding promises is very crucial these days. It is an important pattern to be followed in every JavaScript heavy application. There are several implementations of promises, including Q, jQuery’s deferred API, Angular’s $q (inspired from Q), RSVP, when.js and so on. Promises got a place in the ES6 specification as well. It is already implemented in latest versions of many of the major browsers.

Happy promising!



About Author : 
Name :S Ravi 
Twitter : https://twitter.com/SRavi_Kiran
Bio: Software Professional, Passionate about Microsoft technologies, Blogger, Love to pass time with Music and Cricket

0 comments:

Post a Comment

...