0

My code:

var total_cases  = 0;
var new_cases    = 0;
var total_deaths = 0;

fetch('https://covid.ourworldindata.org/data/owid-covid-data.json')
  .then(res => {
    return res.json()
  })
  .then (raw_data => {

    for (const key in raw_data) {
      const country      = raw_data[key];
      const country_data = country.data;
      const latest_data  = country_data[country_data.length - 1];

      console.log(latest_data);

      if (country.location != "World") {
        if (latest_data.total_cases != null) {
          total_cases += latest_data.total_cases;
        }
        if (latest_data.new_cases != null) {
          new_cases += latest_data.new_cases;
        }
        if (latest_data.total_deaths != null) {
          total_deaths += latest_data.total_deaths;
        }
      }
      console.log(total_cases); /*It will give a result for every loop*/
    }
  })

document.getElementById("total_cases").innerHTML  = total_cases;
document.getElementById("new_cases").innerHTML    = new_cases;
document.getElementById("total_deaths").innerHTML = total_deaths;

If I do this:

<div id="total_cases"></div>

The result is 0. What is the code to change? I know that someone may already answered similar question about function, but I still don't understand about scope of fetch.

  • You need to move your `innerHTML =` calls inside the `.then` (outside the `for` loop but inside the same function) – Wex Jan 30 '21 at 17:33
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – evolutionxbox Jan 30 '21 at 18:19

1 Answers1

0
var total_cases  = 0;
var new_cases    = 0;
var total_deaths = 0;

fetch('https://covid.ourworldindata.org/data/owid-covid-data.json')
.then(res => {
  return res.json()
})
.then (raw_data => {

for (const key in raw_data) {
  const country      = raw_data[key];
  const country_data = country.data;
  const latest_data  = country_data[country_data.length - 1];

  console.log(latest_data);

  if (country.location != "World") {
    if (latest_data.total_cases != null) {
      total_cases += latest_data.total_cases;
    }
    if (latest_data.new_cases != null) {
      new_cases += latest_data.new_cases;
    }
    if (latest_data.total_deaths != null) {
      total_deaths += latest_data.total_deaths;
    }
  }
  console.log(total_cases); /*It will give a result for every loop*/
}

document.getElementById("total_cases").innerHTML  = total_cases;
document.getElementById("new_cases").innerHTML    = new_cases;
document.getElementById("total_deaths").innerHTML = total_deaths;

})

Move the assignment to within the 'then' context

Kyle
  • 1,463
  • 1
  • 12
  • 18