3

我有这段代码:

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

我调用asynchronous_function数组的每个元素,一旦函数执行,它就会触发一个回调。我在回调中有一些过程,只有当这个回调是所有调用的最后一个返回时,我才想执行asynchronous_function。有没有办法在不污染太多代码的情况下实现这一点?

谢谢

4

2 回答 2

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()
         }
    });
}
于 2013-07-09T09:14:59.997 回答
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.
于 2013-07-09T10:19:44.587 回答