简体   繁体   中英

Array pushes data fetched from an api twice

I'm making a call to an api and I'm using async/await. I'm pushing the response data to a global array, but for some reason it is pushing it twice. I'm making two fetch requests, receiving the response, pushing it to an array, and then console logging the data array. How can I prevent it from pushing the data to the array twice?

 var data = [];
const getData = async () => {
  const f1_data = await 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);
      console.log(data);
    })

  const f2_data = await 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);
      console.log(data);
    })
};
getData();

Expected output Example: 56789, 89768 Output 56789, 56789, 89768, 89768

As other suggested, since you are using aysnc and await , might as well get rid of the .then() flow.

It seems like your getData() has been called multiple times, it is unsafe to keep data array outside of your getData function block. You might want to do something like this: (takes few seconds to get the api data..)

 const getData = async () => { const url = 'https://api.covid19api.com/country/' const query = '?from=2020-12-31T00:00:00Z&to=2021-01-01T00:00:00Z'; let data = []; const f1_data = await fetch(`${url}singapore${query}`); const f1_json = await f1_data.json(); data.push(f1_json[0].Confirmed); const f2_data = await fetch(`${url}malaysia${query}`); const f2_json = await f2_data.json(); data.push(f2_json[0].Confirmed); return data; }; const logData = async () => { let data = await getData(); console.log(data); } logData();

return the data from your async getData function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM