I am calling an API to get some values and make a sum in the function getValues() which works fine. The problem is that the response (res.render) sends theTotalTests value before the function getValues() is performed. I tried to use async/await for solving the order of execution, but still couldn't make it work.
router.get("/", async function(req,res){
var totalTests = 0;
totalTests = await getValues();
console.log(totalTests); //this shows 0, but I expected to show the total sum after performing the for loop
res.render("landing", {totalTests: totalTests});
function getValues(){
for(var i=0; i<6; i++){
request({url: districtsUrls[i], json:true}, function(err, res, json){
if (err) {
throw err;
} else {
totalTests = totalTests + json.length;
console.log(totalTests); //this shows the correct sum everytime the loop runs
}
}
)}
return totalTests;
}
});
After this is performed, the console shows:(0 68 176 286 429 566 696) I expect the first value to be 696 (the one after all the loop is run) and not 0 (before the function is executed). I don't know what am I missing.
PS. This is my first time here, I hope I can start contributing to the community. Any feedback for improving the description is also welcome :)