I need to send multiple get requests in a loop, and the callback that processes the response needs the index of the loop in order to combine the response data with the data I already had about each object.
From this, I know how to create a single request and use a callback to pass extra parameters. I am also able to send multiple requests and use XMLHttpRequest.onreadystatechange to set a function for the result.
I tried combining the two solutions, but because it's a loop, the variables change after each iteration and all the responses end up being called with the parameters of the last iteration of the loop. I thought using var indexOfProject = i;
inside the loop would solve the problem, but it didn't. Here's my code:
var count = 0;
var queryProjects = 2;
var totalNeeded = queryProjects;
var apicallback = function(project, index) {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log("processing response, index, project : " + index);
console.log(project);
var objResponse = JSON.parse(xmlHttp.responseText);
_projectsData.projects[index]['lastUpdateTime'] = objResponse['updated_at'];
count++;
if (count==totalNeeded){
console.log("got all responses!");
//TODO:
}
}
};
for (var i = 0; i < queryProjects; i++) {
var indexOfProject = i;
if (repos[i] != null) {
var theUrl = "https://api.github.com/repos/" + repos[i][0];
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
apicallback(_projectsData.projects[indexOfProject], indexOfProject);
}
console.log("sent request!");
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
else {
totalNeeded--;
}
}
I also tried this,
xmlHttp.onreadystatechange = apicallback(_projectsData.projects[indexOfProject], indexOfProject);
but it was even worse because the callback is only called once, when readystate==1
.