Javascript How to store and return responses from multiple async API calls
<p>I have the following function that calls an API several times:</p>

<pre><code>function define(arr, callback) {
    var client = [];
    var definitions = {};
    for (var i = 0, len = arr.length; i &lt; len; i++) {
        (function (i) {
            client[i] = new XMLHttpRequest();
            client[i].onreadystatechange = function () {
                if (client[i].readyState == 4 &amp;&amp; client[i].status == 200) {
                    definitions[arr[i]] = client[i].responseText;
                }
            };
            client[i].open('GET', 'http://api.wordnik.com:80/v4/word.json/' + arr[i] +
                '/definitions?limit=200&amp;includeRelated=false&amp;sourceDictionaries=webster&amp;useCanonical=false&amp;includeTags=false&amp;api_key=...',
                true);
            client[i].send();
        })(i);
    }
    return definitions;
}
</code></pre>

<p>As explained in <a href="https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?noredirect=1&amp;lq=1">How do I return the response from an asynchronous call?</a> the <code>return</code> occurs before the async calls finish causing the function to return an empty object.</p>

<p>Because I have a loop executing many calls I cannot use the solution of <code>status == 200</code> with a callback that returns what I want. </p>

<p>Things I've tried include making a global variable object and a callback that appends new key value pair to it every time it is called. This doesn't work for the same reason the original code doesn't. </p>

<p>I've also attempted to make a callback that returns the object and passing it to another function that doesn't make the call until a condition is met. This seems like the most promising path but I'm unsure of what condition I could use that would be true only after all async calls are finished as the callback would only have access to variables passed to it as arguments.</p>