Friday, November 21, 2014

javascript promises

I used to wonder what are promises for a long time...then I saw a video regarding the topic...and one thing comes to mind...

Code Cleanup...

Or rather, it aids in easy understanding, readability, and thus making it more manageable.

Now here is my explanation. I assume you have worked with jQuery show, hide, fadeIn, fadeOut api's. Here is how a fadeIn works.

$(function(){
  var d = $('#div').hide();
  $(document).click(function(){
    d.fadeIn(5000);
  });
});
View in js bin - example 1

This is a simple example. However, there is an overload for fadeIn which enables us to execute code once the animation completes as shown in the below example...

$(function(){
  var d = $('#div').hide();
  $(document).click(function(){
    d.fadeIn(5000, function(){
      alert('fadeIn completed');
    });
  });
});
View this in JS Bin - example 2

Now say there are few elements you want to show up one-after-another. Shown below is the traditional way of coding for this requirement:

$(function(){
  $('li').hide();
 $('input').click(function () {
  $('#li1').fadeIn('slow', function () {
   $('#li2 ').fadeIn('slow', function () {
    $('#li3').fadeIn('slow');
   });
  });
 });
});
View in JS Bin - example 3

You can see there are a lot of nested callbacks. At a look its hard to follow what is happening. Imagine writing the same for a variable number of li elements...

Here is the refactored version that uses promises:

$(function(){
 $('li').hide();

 var fadeInFunc = function (obj) {
  var deferred = $.Deferred();
  obj.fadeIn('slow', function () {
   deferred.resolve();
  });
  return deferred.promise();
 };

 var funcWrapper = function (obj) {
  return function(){
   return fadeInFunc(obj);
  };
 };

 $('input').click(function () {
  fadeInFunc($('#li1'))
   .then(funcWrapper($('#li2')))
   .then(funcWrapper($('#li3')));
 });
});
View in js bin - example 4

So we had to write a bit of deferred functions and function wrappers...hence there is a bit of extra code...But it tries to convey, what our objective was...

Or if you completely lost the point rename funcWrapper to fade try reading the code again...

Or doesn't it?! Do share your thoughts...

There is a lot more to promises than what's shown here. You should go check the jquery page on $.Deferred() usage and various scenarios.

If you are in a mood to be tested with what you've gained from reading this post, I suggest you try writing code to sequentially fadeIn variable number of li elements...

Happy coding...

No comments: