How to extract data from a function call

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

[   ]
0: data: (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
source: [{…}][[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)

but when I tried

console.log(testData[0])
OR
console.log(testData.data[0].data['ID Nation'])

It says undefined

Were you doing this?

test()
  .then(res => testData.push(res))

console.log('testData', testData[0])

If so, you are console logging testData before the callback assigned to .then is called — It’s asynchronous.

By callback I mean (res) => testData.push(res)

All code in the global execution context is executed before asynchronous code.

e.g.

setTimeout(() => console.log('last'), 0) // asynchronous, callback executed sometime later
console.log('first')

// outputs
first
last

What happens when you try this instead?

test()
  .then(res => testData.push(res))
  .then(() => console.log('testData', testData[0]))

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.

A quick google. This might be worth a read.

2 Likes

Update your code to something like this

// 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();

Good luck