As a beginner in AJAX, I am facing a challenge where I need to set a variable inside a for loop and then use that variable's value later on. The key is to make this process synchronous, which means stopping the scripts from executing until the loop finishes running and returns the new value of the function.
If anyone has a more efficient way to retrieve the value from the for loop after it completes, I would greatly appreciate your advice. Ideally, I want to seamlessly incorporate the value into my code without resorting to using the setTimeout()
hack as it feels like a workaround rather than a proper solution.
var getCount = function getCount(res) {
count = { active: 0, closed: 0 }; // Variable declaration
for(i=0; i<=res.length; i++) {
if(res[i].status == 'active') {
count.active++;
} else {
count.closed++;
}
}
return count; // Returning the updated count variable
};
getCount(result);
console.log(count); // I need the result of the for loop here
// Current output shows both properties of count object as 0;