Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Deferred with an array of functions

I have an object full of functions like so:

var functions = {
    fun1 : function(){ ... }
    fun2 : function(){ ... }
    fun3 : function(){ ... }
};

The object keys are all referenced inside an array like so:

var funList = ['fun1','fun2','fun3'];

I have been using the array to run through all of the functions:

$.each(funList, function(i,v){
    functions[v].call(this, args);
});

My problem is this, I need some way to defer the running of all of the functions such that:

  1. In the $.each loop, the functions run serially
  2. Some method to defer the running of subsequent code until after all functions in the array/object have completed.

I've read that I should be using the $.map method for this, but I'm having a hard time wrapping my mind around it.

like image 695
ValZho Avatar asked Aug 06 '12 18:08

ValZho


2 Answers

Wow... that was an exercise—$.Deferred() was a little hard to get my mind wrapped around, but I got it all working how I wanted! I don't know how streamlined this is—perhaps others can make it more efficient.

The gist of it is to create a chain of deferreds using .pipe().

EDIT: My code (below) does not accommodate less than 2 objects in the reference key list. I updated the jsfiddle to work with key lists of any size.


You can see all of the following working on JSFiddle Here: http://jsfiddle.net/hBAsp/3/


Here's a step-by-step of how I solved it:

  1. Start with an object full of functions and an array of reference keys (in the order you want them processed). The functions should expect to receive a deferred object to resolve on completion:

    var obj = {
        one: function(dfd){
            /* do stuff */
            dfd.resolve();
        },
        two: function(dfd){...},
        three: function(dfd){...},
        etc...
    };
    var keys=['one','two','three', etc...];`
    
  2. Create main deferred wrapper passing the promise into the initialization function. We'll be adding the code to the function as we go:

    var mainDeferred = $.Deferred(function(mainDFD){
    
  3. Inside of that initialization function, create an array of deferreds, manually creating the first deferred object:

    var dfds = [$.Deferred()];
    
  4. Next, use a for loop to go through the second through the next-to-last items in our key list. We will be:

    1. creating a deferred object for each item we step through
    2. setting up an anonymous function that will run the key-associated function from our obj, passing to it for resolution our newly created Deferred object
    3. piping that newly-created function onto the previously created Deferred object (which is why we had to create the first one manually)
    4. You must use an enclosed loop in the for list to get past JavaScript scoping problems

      for (i=1; i<keys.length-1; i++){
          (function(n){
              dfds.push($.Deferred());
              dfds[i-1].pipe(function(){
                  obj[keys[n]].call(this,dfds[n]);
              });
          })(n);
      };
      
  5. Manually create the last anonymous function and pipe it onto the next-to-last deferred object in our list. We do this one manually because we want to pass to it the main deferred object for resolution so that the whole shebang will fire as complete as soon as the last process has run:

    dfds[keys.length-2].pipe(function(){
        obj[keys[keys.length-1]].call(this,mainDFD);
    });
    
  6. Now that our whole pipeline is built, all we have to do is fire off the first object and assign it the first deferred for resolution:

    obj[keys[0]].call(this,dfds[0]);
    
  7. Just have to close up our main deferred initialization function (this will all fire as soon as the deferred is created:

    });
    
  8. Now we can also pipe a function to the main object to run after all of our previous elements have run:

    mainDeferred.pipe(function(){
        /* do other stuff */    
    });
    
like image 161
ValZho Avatar answered Sep 18 '22 22:09

ValZho


I think you can use pipe to pipe your callback function as an array. Here is an example.

var a = $.Deferred();

var b = $.Deferred();

var c = $.Deferred();

var checkA = function() {
  console.log('checkA');
  return a.resolve();
};


var checkB = function() {
  console.log('checkB');
  return b.resolve();
};

var checkC = function() {
  console.log('checkC');
  return c.reject();
};

checkAll = $.Deferred().resolve().promise();
checkAll = checkAll.pipe(checkA);
checkAll = checkAll.pipe(checkB);
checkAll = checkAll.pipe(checkC);

checkAll.done(function() {
  return console.log('checkAll done');
}).fail(function() {
  return console.log('checkAll fail');
});

the output will be

"checkA"
"checkB"
"checkC"
"checkAll fail"

You can change the result "resolve" to "reject" in check functions if you want to see the different result. for example: If you change checkA to be reject.

var checkA = function() {
  console.log('checkA');
  return a.reject();
};

The output will be

"checkA"
"checkAll fail"

It won't go checkB and checkC because checkA is rejected. So that you can call the function with an array

funList = [checkA, checkB, checkC];
for(var i=0; i<funList.length; i++){
  checkAll = checkAll.pipe(funList[i]);
}

Note. You have to make sure the callback always return the Deferred object.

like image 40
Blackbingo Yan Avatar answered Sep 22 '22 22:09

Blackbingo Yan