I have the following function that calls an API several times:
function define(arr, callback) {
var client = [];
var definitions = {};
for (var i = 0, len = arr.length; i < len; i++) {
(function (i) {
client[i] = new XMLHttpRequest();
client[i].onreadystatechange = function () {
if (client[i].readyState == 4 && 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&includeRelated=false&sourceDictionaries=webster&useCanonical=false&includeTags=false&api_key=...',
true);
client[i].send();
})(i);
}
return definitions;
}
As explained in How do I return the response from an asynchronous call? the return
occurs before the async calls finish causing the function to return an empty object.
Because I have a loop executing many calls I cannot use the solution of status == 200
with a callback that returns what I want.
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.
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.