1

I'm working on a very simple covid comparer project, and I've completed most of it but there is one problem. I want to push the result to a global array named data, but it's not working because the data is still loading when the data is pushed to the array. I've inserted the necessary code, not all of it.

var data = []; //global array
    function getData() {
 fetch(url + countryOne.value)
 .then(response => response.json())
  .then((result) => {
 var index = result.length - 1;
 var confirmed = result[index].Confirmed;
 textOne.textContent = result[index].CountryCode + " TOTAL CASES : " + confirmed;
 data.push(confirmed); //trying to push data

 
 })
 
    fetch(url + countryTwo.value)
 .then(response => response.json())
 .then((result) => {

 var index = result.length - 1;
 var confirmed = result[index].Confirmed;
 textTwo.textContent = result[index].CountryCode + " TOTAL CASES : " + confirmed;
 data.push(confirmed);
 
 })
 

}

As you can see I'm fetching the data, working with the response, and then pushing the data into a global array. The problem is that the data is not pushing into the array. I believe I'm having the problem because the array is pushing before the data from the api has loaded. How can push the data to the array after the data has loaded?

Love2Code
  • 440
  • 6
  • 19

2 Answers2

1

Try like this, await for fetch and push response details to data

const getData = async () => {
  const data = [];

  const f1_data = await fetch("https://swapi.dev/api/people/1/")
    .then((res) => res.json());
  data.push(f1_data.name);

  const f2_data = await fetch("https://swapi.dev/api/people/2/")
    .then((res) => res.json());
  data.push(f2_data.name);
  
  console.log(data);
};

getData();
Siva K V
  • 10,561
  • 2
  • 16
  • 29
0

Perhaps you need to see the following structure:

async function getData(){
  const data = [];
  let resp, jsonArray;
  resp = await fetch(url+countryOne.value); jsonArray = await resp.json();
  let index = jsonArray.length-1, confirmed = jsonArray[index].Confirmed;
  textOne.textContent = jsonArray[index].CountryCode + ' TOTAL CASES : ' + confirmed;
  data.push(confirmed);
  resp = await fetch(url+countryTwo.value); jsonArray = await resp.json(); 
  index = jsonArray.length-1; confirmed = jsonArray[index].Confirmed;
  textTwo.textContent = jsonArray[index].CountryCode + ' TOTAL CASES : ' + confirmed;
  data.push(confirmed);
  return data;
}
// get like
getData().then(data=>{
  console.log(data);
});
// or in another async function
async function test(){
  const data = await getData();
  console.log(data);
}
test();
StackSlave
  • 10,613
  • 2
  • 18
  • 35