How do I return the accumulated results of multiple (parallel) asynchronous function calls in a loop?
<p>I have a function <code>foo</code> which makes multiple (parallel) asynchronous calls in a loop. I need to somehow wait until the results of all of the calls are available. How can I return the full results from <code>foo</code>, or otherwise trigger some processing after <em>all</em> of the data is available?</p>

<p>I tried adding each result to an array, but then the array isn't populated until after the point where I need to use it.</p>

<pre><code>function foo() {
    var results = [];

    for (var i = 0; i &lt; 10; i++) {
      someAsyncFunction({someParam:i}, function callback(data) {
        results.push(data);
      });
    }
    return results;
}

var result = foo(); // It always ends up being an empty array at this point.
</code></pre>

<p>Note: this question is deliberately generic along the lines of the existing generic <a href="https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call">"How do I return the response from an asynchronous call?" question</a>. That question has some excellent answers, but doesn't cover multiple async calls. There are some other questions that mention multiple calls, but I couldn't find any loop-based ones, and some only had jQuery answers, etc. I'm hoping here for some generic techniques that don't depend on a particular library.</p>