2013-07-09 42 views
3

执行一个程序我有这样一段代码:仅在最后返回回调

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

我打电话asynchronous_function对于阵列中的每个元素,并且一旦执行功能,它触发一个回调。我在回调中有一些步骤,我只想执行,如果这个回调是所有被调用的asynchronous_function返回的最后一个回调。有没有办法实现这一点,而不会污染太多的代码?

感谢

+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() 
     } 
    }); 
} 
+0

我觉得你只是想'numTimesCalled === some_array.length '。不要减去1. –

+0

是的,完全正确。我的brainfart。 – Reason

+2

“计算机科学中存在两个难题:命名事物,缓存过期和逐个错误。” –

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.