一个简单的解决方案是计算你的回调:
var results = [];
function final_callback(results)
function callback(result){
results.push(result):
if (results.length == number of requests){
final_callback(results);
}
}
一个更体面的解决方案是使用带有计数器的 EventEmitter 事件:
my_eventEmitter.on('init_counter',function(counter){
my_eventEmitter.counter=counter;
});
my_eventEmitter.on('result',function(result){
if( my_eventEmitter.counter == 0 ) return;
//stop all callbacks after counter is 0;
my_eventEmitter.results.push(result);
my_eventEmitter.counter--;
if( my_eventEmitter.counter == 0 ){
my_eventEmitter.emit('final_callback');
}
});
my_eventEmitter.on('final_callback', function(){
//handle my_eventEmitter.results here
})
....现在你只需要做你的 for 但在它发送 init_counter 到事件发射器之前
my_eventEmitter.emit('init_counter',50);
for(i=0; i<50; i++) async_function_call(some_params, function(result){
my_eventEmitter.emit('result',result);
});