How do I return the accumulated results of multiple (parallel) asynchronous function calls in a loop?

后端 未结 5 1369
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 09:14

I have a function foo which makes multiple (parallel) asynchronous calls in a loop. I need to somehow wait until the results of all of the calls are available.

5条回答
  •  一向
    一向 (楼主)
    2020-11-29 09:34

    A simple way of doing it would be to trigger a callback once all responses are in the array:

    function foo(cb) {
        var results = [];
    
        for (var i = 0; i < 10; i++) {
          someAsyncFunction({someParam:i}, function callback(data) {
            results.push(data);
    
            if(results.length===10){
              cb(results);
            }
          });
        }
    
    }
    
    foo(function(resultArr){
        // do whatever with array of results
    });
    

    Only difference from the Promise.all approach is the order of the results is not guaranteed; but that is easily achievable with a few additions.

提交回复
热议问题