-1

So I'm trying to retrieve some data that I'm fetching from an api so that I can build a chart with Chart.js with that retrieved data.

The problem is that I am declaring 2 arrays to store the data returned by the api, but when I push the data it returns undefined and I can't understand why.

Here's the function responsible for what I described above:

async function getChartData(){

    const xdata = []
    const ydata = []

    const data = await (await fetch('http://projetoti.test/api/api.php?nome=all')).json()

    await data.forEach(async (sensor, index) => {

        let sensor_data = await (await fetch(`http://projetoti.test/api/api.php?nome=${sensor.name}&history=true`)).json()

        let xtemp_arr = []
        let ytemp_arr = []

        Object.keys(sensor_data).forEach(sData => {
            xtemp_arr.push(sensor_data[sData].value)
            ytemp_arr.push(sensor_data[sData].time)
        })

        xdata.push(xtemp_arr.slice())
        ydata.push(ytemp_arr.slice())
    })

    console.log(xdata)
    return { xdata, ydata}

}

The confusing part is, when I console.log(xdata) inside the data.forEach() it consoles the expected even when it quits the forEach() xdata consoles the expected but it returns undefined.

I know that in JavaScript when we push an array what is actually happening is that the reference of the array is being copied.

So I tried to solve that by making a copy of the temporary arrays with .slice(). But still, xdata and ydata are returning undefined.

Note: Here is the print of the console.log(xdata): [output of console.log(xdata)](https://i.stack.imgur.com/Theuh.png) Can anyone help me understand why this is happening?

Goncalo
  • 1
  • 1

1 Answers1

0

The await data.forEach() does not do what I believe you may be expecting it to. The forEach() method returns undefined and the await will return immediately. The statements afterwards, console.log(xdata) and return { xdata, ydata} will then execute immediately afterwards. Meanwhile, the function within the forEach() will still be running, meaning that inside this function, the .push() calls happen after getChartData() has already returned and hence why you might not be getting what you expect.

Wongjn
  • 8,544
  • 2
  • 8
  • 24
  • Thanks for your help. I didn't know that `forEach()` returned `undefined`, but now it makes sense to me. – Goncalo Apr 15 '23 at 13:05