在每个内部回调一个when()。然后()

时间:2012-04-24 08:36:42

标签: jquery callback each apply

我有这段代码:

var getStuff = function(resources, callback, progressCallback){
  var deferreds = [];
  for(var idx = 0; idx < resources.length; idx++){
     ...
     deferreds.push(<some action>);
  }

  jQuery.when.apply(null, deferreds).then(function(){
    callback && callback();
  });
});

所以,如果我用以下方法调用它,这将触发我的回调:

getStuff([
  'foo',
  'bar'
], function(){
  console.log("Finished doing stuff!");
});

问题是:如何进行progressCallback?

类似的东西:

getStuff([
  'foo',
  'bar'
], function(){
  console.log("Finished doing stuff!");
}, function(obj){
  console.log("Doing stuff with obj: " + obj);
});

问候!

1 个答案:

答案 0 :(得分:1)

你可以尝试这种方法(我没试过)

var getStuff = function(resources, callback, progressCallback) {

    var deferreds = [];
        len       = resources.length; // need a variable for later iteration

    for(var idx = 0; idx < len; idx++){
       deferreds.push(<some action>);
    }


    deferreds.reverse();  // So the order of deferred lookup is preserved

    /* we create a named self-executed function, so we can call it when 
       a deferred is done and len variable is decremented */

    (function iterateWhen() {
       if (len--) {
         /* call progress callback */
         progressCallback(deferreds[len]); 
         jQuery.when(deferreds[len]).then(function() {
            iterateWhen();
         });
       }
       else {     
          callback && callback();
       }
    }());

};