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?