0

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 :)

seaona
  • 1
  • 1
  • Asynchronous is the opposite of synchronous...that type of behavior is expected. You could use `setTimeout()` to delay I suppose.... – zer00ne Apr 21 '20 at 14:25
  • No need for `var totalTests = 0;`. But i guess you also have to `await` the rendering of your site. Maybe this can help you to make a Promise of your function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – Alexander Riedel Apr 21 '20 at 14:38
  • The `getValues()` function does not return a promise, so there's nothing to wait for. You'd need to make a promise for the `request()` result, and then `await` that – Bergi Apr 21 '20 at 15:15

0 Answers0