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

"Modify marker icon upon click event in Google Maps by utilizing the loadGeoJson function

I have successfully loaded the markers from a json file using loadGeoJson. While I am able to SET the marker icon/img on load, I am unsure of how to CHANGE it upon click. Is there a way to target the clicked marker and perform a setIcon or similar action ...

Scrolling vertically in an ASP.NET GridView

I have a Grid View embedded inside an IFrame. Everything works perfectly when the number of records fits within the frame. However, if I try to display more records, I encounter an issue where I am unable to click on the Footer Row. It automatically moves ...

Displaying numerous Google maps on a single webpage featuring distinct collections of location markers

Currently, I am utilizing the Google Maps API to showcase two distinct Google maps on a single page. Each map comes with its own set of unique markers that are dynamically generated via Wordpress from various custom post types. While one map is successful ...

Guide to sending JSON data through the Wufoo Entries API

It seems the current documentation is lacking in detailing the proper procedure for submitting forms via Ajax. Although there is The Entries POST API, it specifically discusses xml and lacks an example payload. Upon further investigation, I discovered Wuf ...

Vue - Implementing plugin as a prototype functionality

For notifications in my application, I've incorporated the euvl/vue-notification library. Each time I need to notify the user, I have to include the following code: If I'm within a Vue component: this.$notify({ group: 'panel', ...

Steps to develop a log-in API using Node.js

In the process of developing my web application, I have utilized node js exclusively for all functionalities and the web user interface has been successfully implemented. An issue that has come to light is that users are able to access the services API wi ...

The issue with Nextjs getStaticPaths is that it is not retrieving data from Firebase Firestore

I'm encountering an issue with fetching dynamic data from firestore in nextjs using getStaticPaths. While rendering the data from firestore with getStaticProps works, I'm facing a problem when trying to access specific item details as it leads me ...

Toggle the visibility of dropdown list items in different ways: Add or Remove, or Show or

Currently, I am working on a project that involves 3 drop down lists for security questions. I have implemented javascript functionality that triggers an alert when a selection is made in any of the drop down boxes. My challenge now is figuring out how t ...

Determine if an array of objects within React JS contains additional objects

I need assistance in displaying the <div className="songs-list-header-col">Album</div> only if the tracks array contains the artist property as an object. In cases where the artist is not an object, I do not want to display the <di ...

Utilizing Dynamic CSS in Ionic Framework with AngularJS

While working with Ionic 1, I attempted to modify the background color and text color of the ion-nav-bar element, but unfortunately, my changes were not taking effect. Here is what I tried using in run() : $rootScope.globalStyleVars = { "backgrou ...

Using AngularJS: Setting a default value for the select option when the current selection is not valid

I am currently working on a cascading select feature where the value in the first dropdown determines the options available in subsequent dropdowns. However, when I change the value in the first dropdown and the previously selected option is no longer val ...

Encountering a problem when verifying if the data is in JSON format using JavaScript

I'm using JavaScript to determine whether an input value is in JSON format, but I've encountered a problem with a specific value. Below is my code explanation. isJSON = async(str) => { try { return (JSON.parse(str) && !!str); ...

Monitoring an object with Angular.js $watch does not detect the addition of a new property as a change

Within my Angular.js directive, I have the following code snippet: scope.$watchCollection(function(){ return StatusTrackerService.eventCollection }, function(){ console.log("ssssssssssss"); console.log(StatusTracker ...

Ways to include input values

In my form, there are 4 text boxes labeled as customer_phy_tot, customer_che_tot, and customer_bio_tot. I want to add up the values entered in these 3 boxes and display the sum in a 4th input box called customer_pcb_tot. customer_bio_obt.blur(function(){ ...

Transforming JSON data into a DataFrame

As a newcomer to JSON, I have combed through various tutorials in an attempt to understand the process better. Seeking additional guidance, I am looking to convert a JSON dictionary into a dataframe using Jupyter notebook/Pandas and eventually save it as a ...

The disconnection event in Node.js socket.io is not being triggered

I've been working on an app using socket io, but I'm having trouble with my disconnect trigger event. I followed the documentation to the letter, but it's still not functioning properly. Strangely enough, it was working just fine a few days ...

The ref.on() method fails to trigger a response from a function, despite producing the intended outcome

I've been working on developing an app called workspace. I previously asked a question, but I've made more additions to the features now. One of the new features is a remarks system. After experimenting with different versions of my code, the ver ...

What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below. const PRODUCTS = [ { brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: ' ...

The link and source attributes are missing from the .ejs template

I am experiencing an issue where the href and src attributes in my .ejs file are not referencing my local files properly. My setup involves node.js and express. Here is a snippet from the .ejs template that is causing the problem. <head> & ...

Failure to load a picture does not trigger onError in the onLoad function

Is there a way to ensure that an image always loads, even if the initial load fails? I have tried using the following code snippet: <img class="small" src="VTVFile4.jpg" onload="this.onload=null; this.src='VTVFile4.jpg?' + new Date();" alt=" ...