Issue with Array.push() method resulting in undefined return value

Currently, I am in the process of fetching data from an API to later use it for creating a visualization using Chart.js. However, I've encountered a problem while trying to store this retrieved data in arrays and then encountering undefined values when pushing the data.

Below is the function responsible for handling this process:

async function getChartData(){

    const xdata = []
    const ydata = []

    const data = await (await fetch('http://exampleapi.com/api/data')).json()

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

        let sensor_data = await (await fetch(`http://exampleapi.com/api/data/${sensor.name}`)).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 puzzling part is that even after logging the expected output with console.log(xdata) inside the data.forEach(), the final result turns out to be undefined.

I am aware that pushing an array in JavaScript involves copying the array reference. To address this issue, I attempted to create copies of the temporary arrays using .slice(). Despite these efforts, xdata and ydata still show undefined values upon returning them.

Note: For reference, you can see the

console.log(xdata): [output of console.log(xdata)](https://i.exampleimage.net/example.png) 
Could someone offer insights on why this behavior is occurring?

Answer №1

It's important to note that when using await data.forEach(), the behavior may not align with your expectations. The forEach() method actually returns undefined, causing the await to resolve immediately. This means that subsequent statements such as console.log(xdata) and return { xdata, ydata} will be executed right away. However, the inner function within the forEach() will continue running in the background. As a result, any .push() calls within this function will occur after the initial getChartData() has already completed its return operation, potentially leading to unexpected outcomes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery email validation failing to function

I am new to JQuery and have created a basic validation script to verify email addresses. However, it does not seem to be working properly. Can anyone provide guidance on how to correct this issue? <script> $( "#email" ).blur(function() { var ...

Next.js implementation of dynamic routing

Hello, I'm currently facing a challenge while working with dynamic routes in Next.js. The file in question is named [type].js, and it contains the following code: import React from 'react'; import AuthSection from 'components/AuthSectio ...

Transmitting an Associative Array from one PHP script to another using AJAX communication in PHP

After receiving an associative array from PHP via $_GET through the following URL: example.com/example.php?itemcount[A]=2&itemcount[B]=3 The result of using json_encode() turns out to be: { "A" : "2", "B" : "3" } I am now looking to send this data to ...

Constructor for Mongoose schema not being detected

I am facing an issue in my Node server where I am using Mongoose with a User schema to create a signup function. The error message I am receiving is: TypeError: this is not a constructor This error is coming up in the following code block: var mongoos ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

Incorporating input fields into an HTML form

I'm looking to enhance my form by adding input fields dynamically through the JavaScript function when I click on the add button: let i = 0; function increment() { i += 1; } function addFieldFunction() { let newDiv = document.createElement(&apos ...

What is the best way to flip cards with the onClick event in JavaScript?

My cards are currently facing down with the code* provided. What steps should I take to flip them face up using onClick functions? Furthermore, how can I store the IDs in an Array and use them to retrieve images from my image collection? HTML <table s ...

Issue with loading STL file in THREE.js: "Uncaught RangeError: offset exceeds the bounds of DataView"

I am currently working on creating a small viewer for stl files using javascript. To achieve this, I am utilizing the library three.js along with the STLLoader module. For file upload functionality, I have integrated an API in node.js which allows me to se ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

Laravel vue infinite scroll failing to load additional content

I've been trying to implement the infinite scroll feature from Element UI in my app, but for some reason, it's just not working. Here's a snippet of my code: Code script // Your JavaScript code goes here ...

Using NodeJS to incorporate an array of strings into a PostgreSQL query

I'm currently working on a PostgreSQL query in Node.js using a pool created with the node-postgres package. The goal is to insert a new row into a table where one of the columns is of type text[]. Here's my code snippet: pool.query('INSERT I ...

Protractor gives back an object when it should return the value of element.getText() instead

Having trouble understanding why it's returning an object instead of the text value, here is some test code: describe('columns swap', function () { describe('location column ', function () { it('should swap right ...

Using a series of nested axios requests to retrieve and return data

Currently, I am utilizing Vue and executing multiple calls using axios. However, I find the structure of my code to be messy and am seeking alternative approaches. While my current implementation functions as intended, I believe there might be a more effic ...

Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project. One remaining crucial task is to extract the result from the callback functions so that I can continue working with it. Below is a snippet of ...

Issues with $routeProvider in a web page hosted by Express.js

As I embark on creating my very first Express.js/Angular application, I'm encountering a challenge with the $routeProvider in the page served by the Express.js application. Let's take a look at the server.js: var express = require('express& ...

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

Is it possible to apply draggable functionality in the same way you attach events to an arbitrary node and a selector?

Here is a possible solution: function myFunction(){/*.....*/} $("body").on("click", "li.itemlist", function(){ alert("ping"); }); This code sets up a click event for all li.itemlist elements under the body element. However, is there a way to sim ...

Encountering an issue while attempting to convert a string into JSON from a .json file within a Node.js environment

var jsonObject = collages; file.writeFile('collage.json', JSON.stringify(jsonObject), function(err){ if (err) throw err; console.log('Success'); }); var result = ''; result += file.readFile('collage.json', ...

The issue with npm run build may be caused by a compatibility issue between TypeScript and lodash

Currently using typescript version 4.5.2 and lodash version 4.17.21 Running the command npm run build will trigger tsc && react-scripts build The following errors were encountered during the build process: node_modules/@types/lodash/common/objec ...

Limiting the functionality of API's to be exclusively accessible within the confines of a web browser

Currently, I am working with node js and have implemented policies to restrict API access from sources other than the browser. In order to achieve this, I have included the following condition in my code: app.route('/students').all(policy.checkH ...