I am trying to make multiple requests on the server within a loop for. I found some tips here and implemented the suggested solution. However, it does not seem to work.
var valuePlan = [];
function getValue(id) {
var f = (function(){
var xhr = [], i;
for(i = 0; i < id.length; i++){ //for loop
(function(i){
xhr[i] = new XMLHttpRequest();
url = "get.php?id=" + id[i] + "&for=monthly";
xhr[i].open("GET", url, true);
xhr[i].onreadystatechange = function(){
if (xhr[i].readyState === 4 && xhr[i].status === 200){
console.log('Response from request ' + i + ' [ ' + xhr[i].responseText + ']');
valuePlan.push(xhr[i].responseText.replace(".", ","));
}
};
xhr[i].send();
})(i);
}
})();
};
getValue([48,52,50]);
console.log(valuePlan[0]);
The problem that when I use console.log(valuePlan[0]); in console it returns undefined, and if it uses console.log(valuePlan); returns the arrays with the correct values. Can you understand that?
The variable is already defined as global, and even then I can not fetch the individual values of it.
iwhere when the callback executes, the value ofiis wrong. And the other issue is you try to order a pizza and eat it before it gets delivered. The loop finishes before the Ajax calls are done so you log before it is complete.asynchronoussovaluePlanwill not hold the result values immediadly but at the ends of the ajax calls, you should definitly usePromiseto handle this type of scenario