I have a getData () {...}
function, inside it with fetch ()
and .then
an object is populated which is declared in the global scope with var. After describing the body of the function, I immediately run it: getData ();
then I output the object filled inside the function to the console. The object is displayed as it should, all the data is there. BUT! as soon as I try to do some kind of manipulation with the object, for some reason it is always empty and its length = 0
. What could be the problem and how to fix it?
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
var countriesData = {};
function getData() {
fetch('https://api.covid19api.com/summary', requestOptions)
.then(res => res.json())
.then(res => {
covidGlobalCases.innerHTML = res.Global.TotalConfirmed;
});
fetch('https://api.covid19api.com/summary', requestOptions)
.then(res => res.json())
.then(res => res.Countries.forEach((country) => {
//console.log(country.Country + ': ' + country.TotalConfirmed);
countriesData[country.Country] = country.TotalConfirmed;
}));
}
getData();
console.log(countriesData);
console.log(countriesData.length);
var sortedCountriesData = Object.keys(countriesData).sort(function(a, b) {
return countriesData[a] - countriesData[b];
});
console.log(sortedCountriesData);
I tried to rewrite it, but I don't understand how to correctly rewrite this line.
.then(res => res.Countries.forEach((country) => {
//console.log(country.Country + ': ' + country.TotalConfirmed);
countriesData[country.Country] = country.TotalConfirmed;
}));
async function getData() {
const covidGlobalCases = document.querySelector('.general-info__global__cases');
const tableCasesByCountry = document.querySelector('.table__cases__by__country');
let res = await fetch('https://api.covid19api.com/summary', requestOptions);
let data = await res.json();
covidGlobalCases.innerHTML = await data.Global.TotalConfirmed;
res = await fetch('https://api.covid19api.com/summary', requestOptions);
data = await res.json();
data = await data.Countries.forEach((country) => {
countriesAllConfirmed[country.Country] = country.TotalConfirmed;
tableCasesByCountry.insertAdjacentHTML('beforeend', `
<div class="table__tr">
<span class="county__cases">${countriesAllConfirmed[country.Country]}</span> <span class="county__name">${country.Country}</span>
</div>
`);
})
return countriesAllConfirmed;
}