仅在最后返回的回调时执行过程

时间:2013-07-09 09:08:47

标签: javascript callback

我有这段代码:

for(var i = 0; i < some_array.length; i++){
    some_array[i].asynchronous_function(some, parameter, callback(){
         some_procedure();
    });
}

我为数组的每个元素调用asynchronous_function,一旦执行了函数,它就会触发一个回调。我在回调中有一些程序,如果这个回调是所有被调用的asynchronous_function的回调,我想执行 。有没有办法实现这一点而不会过多地污染代码?

由于

2 个答案:

答案 0 :(得分:4)

计算调用asynchronous_function的次数。当它被称为some_array.length次时,你可以调用some_procedure()。像这样的东西

var numTimesCalled = 0;
for(var i = 0; i < some_array.length; i++){
    some_array[i].asynchronous_function(some, parameter, function(){
         numTimesCalled ++;
         if (numTimesCalled === some_array.length) {
             some_procedure()
         }
    });
}

答案 1 :(得分:1)

这应该做的工作:

// callAll : calls methodName method of all array items.
//               uses the provided arguments for the call and adds the callback
//               methodName is async and must accept a callback as last argument
//               lastCallBack will get called once after all methods ended. 
//
function callAll(anArray, methodName, lastCallBack ) {
   // create closure to keep count of calls
   var callCount = anArrray.length;
   // build function that calls lastCallBack on last call
   var callIfLast = function() { callCount--; if (!callCount) lastCallBack(); };
   // build function arguments
   var args = arguments.slice(3).push(callIfLast);
   // call all functions
   anArray.forEach( function(item) { item[methodName].apply(item, args ) } );
 }

callAll(myArray, 'meth', myCallback, 1, 2, 3);
// ...
// --> will call myArray[i].meth(1, 2, 3, callIfLast)  for all i.
//          and call myCallBack when all calls finished.