I am trying to extract data returned from the following function but it is saying undefined no matter what I’ve tried
async function test (){
const response = await axios.get(
'https://datausa.io/api/data?drilldowns=Nation&measures=Population'
)
return response.data;
}
let testData = [];
test ().then(res=>testData.push(res));
When I do console log(testData), I can see an array of object of length 9 as seen below
It’s late here, so forgive my sketchy response. It would be worth you looking into the event loop and getting an understanding of macro and micro tasks. Node’s event loop is a bit more complex, but this should give you an idea.
// Your async function to fetch the data using Axios
async function test() {
const response = await axios.get(
'https://datausa.io/api/data?drilldowns=Nation&measures=Population'
);
return response.data;
}
let testData = [];
// Using async/await
async function fetchData() {
let data = await test();
testData.push(data);
console.log(testData[0]);
console.log(testData[0].data[0]['ID Nation']);
}
fetchData();