The JSON array retrieved from the $http.GET request is coming back as undefined, which is not expected

Presenting my code below:

function gatherDataForGraph(unit, startTs, endTs, startState, endState){
points = [];
console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState);
$http.get('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState).success(function(data){
    for (var i = 0; i < data.length; i++) {
        points.push({x:getBasicTimeFromEpoch(data[i].ts), y:data[i].data});
    }
  return points;
  });
}

function displayFileStateLineGraph(unit, startTs, endTs){
gatherDataForGraph(unit, startTs, endTs, 1, 2);

console.log(gatherDataForGraph(unit, startTs, endTs, 1, 2));
var dp1= gatherDataForGraph(unit, startTs, endTs, 1, 2);
var dp2= gatherDataForGraph(unit, startTs, endTs, 2,3);
var dp3 = gatherDataForGraph(unit, startTs, endTs, 3,4);
console.log(dp1);
console.log(dp2);
console.log(dp3);
var chart = new CanvasJS.Chart("chartContainer", {
    title: {
      text: "Click on legend items to hide/unhide dataseries"
    },
    legend: {
        cursor: "pointer",
        itemclick: function (e) {
            if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
                e.dataSeries.visible = false;
            } else {
                e.dataSeries.visible = true;
            }
            chart.render();
        }
    },
    data: [{
        showInLegend: true,
        type: "line",
        dataPoints: dp1
    }, {
        showInLegend: true,
        type: "line",
        dataPoints: dp2
    }, {
        showInLegend: true,
        type: "line",
        dataPoints: dp3
         }]
  });
  chart.render();
}
displayFileStateLineGraph("day",1404000000, 1406000000)

Upon running the console.logs, only "undefined" is shown. It's possible that this occurs because the function executes before the JSON call is complete. This issue seems unfamiliar to me.

Answer №1

First and foremost, it's crucial to address the issue with your getLineGraphData function lacking a return value. Additionally, as this function runs asynchronously, you must ensure that you wait for the completion of the success handler before attempting to access the points data.

To rectify this, begin by incorporating a return statement in your code: return $http.get(...). This will result in the function returning a Promise.

Furthermore, in order to successfully access the points data, you need to utilize

promise.then(function(points) { ... })
. This grants you access to the retrieved data within the then function.

In scenarios where you depend on multiple sets of points, it is imperative to await the completion of all operations. You can achieve this by employing `$q.all(...)` method as illustrated below:

$q.all({
    dp1: getLineGraphData(unit, startTs, endTs, 1,2),
    dp2: getLineGraphData(unit, startTs, endTs, 2,3),
    dp3: getLineGraphData(unit, startTs, endTs, 3,4)
}).then(function(dataPoints) {
    var dp1 = dataPoints.dp1, dp2 = dataPoints.dp2, dp3 = dataPoints.dp3;
    ... Create your chart ...
});

Answer №2

When working with the getLineGraphData function, ensure that you are handling the promise returned by $http.get properly. The points should be populated within the success callback of the promise, not directly from the getLineGraphData function itself. Make sure to return the promise from the function and then attach a success callback to it to populate dp1 and other variables accordingly.

 function getLineGraphData(unit, startTs, endTs, startState, endState){
    var points = [];
    console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState);
    return $http.get('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+endState);
 }

var dp1 = [];
getLineGraphData(unit, startTs, endTs, 1, 2).success(function(data){
    for (var i = 0; i < data.length; i++) {
        dp1.push({x:getBasicTimeFromEpoch(data[i].ts), y:data[i].data});
    }
    console.log(dp1);
  });

Ensure that dp1 is successfully printed out as expected.

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

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Unlock the potential of JavaScript by accessing the local variable values in different functions

I've been struggling for days to find a solution to this issue... https://i.stack.imgur.com/KDN7T.jpg https://i.stack.imgur.com/tOfCl.jpg The image above illustrates the challenge I'm facing - trying to apply data values from elsewhere to the ...

Removing double double quotes for Javascript

My problem involves a string that represents longitude/latitude in the format of dd°mm'ss''W (note 2 single quotes after ss). To convert this string into its decimal representation, I am using the following code snippet: function dmsTodeg ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Dynamic popup in RShiny interface with the ability to be moved around

I am currently working on a dashboard project and I am looking to implement a dynamic popup feature that can be moved around. I have been able to create a pop-up, but it remains static. I would like the flexibility for users to drag and position the popup ...

Does Next.js pre-render every page, or does it only pre-render the initial page?

As I dive into the world of nextjs, I'm coming across conflicting information. Some sources claim that nextjs only prerenders the first page, while others suggest that all pages are prerendered by default. This contradiction has left me confused about ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

Utilize the ng-click feature for swiping interactions in Ionic v1

I have a slide page on Ionic V1 that utilizes previous and next buttons. Here is an example: <button id="" class="button button-slide prev no-animation" ng-click="prev()" ng-show="activeIndex > 0" > BACK </button> While the click function ...

Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it. export default { name: 'Home', components: { PokeList, FilterType, SearchPokemon}, data() { r ...

How can we set up a Vue.js component before incorporating it into a template?

Currently, I am working on a Vue single file template where I need to fetch some data (a JWT token) and then use that token to make another request to a graphql endpoint. The Provider Component in my template requires the JWT Token to be set up with the ...

When using angularjs, the $window.location.href may cause the page to load without any

I have a dilemma where I have linked all my CSS and JS files in the index.html file, but subpages are located in a templates directory. When using $window.location.href, only a plain HTML page is returned without any CSS styles. The page renders fine when ...

JavaScript Memoization: Enhancing Performance Through Caching

Recently, I delved into various JavaScript design patterns and stumbled upon memoization. While it seems like an effective way to prevent redundant value calculations, I can't help but notice a flaw in its implementation. Consider the following code s ...

Toggle the visibility of table rows using checkboxes

I'm working with checkboxes to toggle the visibility of specific rows in a table based on their content matching the selected checkbox values. Checkboxes: <input type='checkbox' name='foo1' value='foo1' v-model="sele ...

Can we dynamically add an identical DOM structure by clicking a button using jQuery?

I currently have ten text fields within a single div. I am interested in including another set of ten text fields with the same name, class, and id. Is there a way to recycle the existing DOM structure mentioned above, or will I need to generate and add t ...

Ajax script causes error 403 when loading content while scrolling

Currently in the process of creating a blog using the HubSpot platform. The primary goal is to have blog posts load dynamically as users scroll down the page. I came across a script that claims to achieve this functionality and is designed specifically for ...

Having difficulty showcasing API call results in a Vue.js component

I am currently experimenting with Vue.js in an attempt to showcase results from a Wikipedia API call within a component using the v-for directive. However, I seem to be encountering some backend issues that I cannot pinpoint. To access the jsFiddle link, ...

Navigating through a nested array within a JSON object using Vue.js - a guide

I have a JSON data array that includes outer and inner subarrays. My goal is to loop through both levels and create a table. Below you'll find a snippet of the sample array: { class:'I', subDdiv:[ { ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

What is the best way to determine if a checkbox has been selected in ExtJS?

I have a panel with a checkbox inside it. I am trying to figure out how to check if the checkbox is selected or not using an external function. Can someone please assist me with this? this.currentManagerPanel = new Ext.Panel({ border: false, wid ...

Managing the triggering of the automatic transition in view models

My question is straightforward and requires no elaborate explanation. Can Durandal be configured to control the use of transitions when transitioning between viewmodels? The motivation behind wanting to disable the animation is as follows: I have a sear ...