What causes the promise to fail when executed outside of the loop?

I have been working on adding fusionCharts dynamically to an AngularJS page. I load chart data into a model object, and while the charts do display, they show "No data to display" content.

My app.js:

(function () {

var modelListOfCharts = ["1", "4", "5", "6"];
var model = {};
var app = angular.module('chartDash', ["ng-fusioncharts"]);

app.controller('fussionController',["$scope","DataService", function ($scope, DataService) {
    $scope.chartData = {};

    DataService.getThings().then(function () {
        $scope.myListOfCharts = modelListOfCharts;
        $scope.chartData = model;
    });
}]);

app.service("DataService", ["$http", "$timeout", "$q", function ($http, $timeout, $q) {
    return {
        getThings: function () {
            var dfd = $q.defer();
            $timeout(function () {
                angular.forEach(modelListOfCharts, function(chartId) {
                    $http.get('/FusionCharts/GetChartData/', { params: { chartID: chartId } }).success(function (result) {
                        model[chartId] = result;
                    });
                });
                dfd.resolve(model);
            }, 300);
            return dfd.promise;
        }
    };
}]);
})();

My html:

<div ng-controller="fussionController">
    <div ng-repeat="n in myListOfCharts">
        <h2>Chart number {{n}}</h2>
        <fusioncharts width="100%"
                      height="400"
                      type="MSCombi2D"
                      datasource="{{chartData[n]}}"></fusioncharts>
    </div>
</div>

When I move dfd.resolve(model); inside the loop, it only displays data for one chart.

    app.service("DataService", ["$http", "$timeout", "$q", function ($http, $timeout, $q) {
    return {
        getThings: function () {
            var dfd = $q.defer();
            $timeout(function () {
                angular.forEach(modelListOfCharts, function(chartId) {
                    $http.get('/FusionCharts/GetChartData/', { params: { chartID: chartId } }).success(function (result) {
                        model[chartId] = result;
                        dfd.resolve(model);
                    });
                });

            }, 300);
            return dfd.promise;
        }
    };
}]);

Answer №1

To handle multiple HTTP requests, you need to manage multiple promises and wait for them all to be resolved. Here is an example:

app.service("DataService", ["$http", "$timeout", "$q", function ($http, $timeout, $q) {
    return {
        getThings: function () {
            var arrayOfPromises = [];
                angular.forEach(modelListOfCharts, function(chartId) {
                    arrayOfPromises.push($http.get('/FusionCharts/GetChartData/', { params: { chartID: chartId } }).success(function (result) {
                        model[chartId] = result;
                    }));
                 });

            return $q.all(arrayOfPromises);
        }
    };
}]);

Answer №2

To ensure each chart is loaded properly, you must create a separate promise for every chart and then wait for all of them to be resolved:

app.service("DataService", ["$http", "$timeout", "$q",
  function($http, $timeout, $q) {
    return {
      getThings: function() {
        var promises;

        $timeout(function() {
          promises = modelListOfChart.map(function(chartId) {
            var dfd = $q.defer();
            $http.get('/FusionCharts/GetChartData/', {
              params: {
                chartID: chartId
              }
            }).success(function(result) {
              model[chartId] = result;
              dfd.resolve(model);
            });
            // Might want to include a reject for error handling...

            return dfd;
          });
        }, 300);

        return $q.all(promises);
      }
    };
  }
]);

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

Simple method for implementing a fade effect on a React component with raw JavaScript techniques?

I am seeking a way to have my React component smoothly fade in upon being mounted. The component's outermost DIV starts with inline style display:none. Within the componentDidMount() method, I've written the following code: let el = document.que ...

jQuery not displaying Div elements as expected

After experimenting with the Coverflow technique and adapting it to work with a div, I have encountered a slight issue. Below is the HTML code I am using: <html> <head> <meta http-equiv="Content-type" content="text/html; ...

Exploring the World of Regex Character Sets and Their Contents

Currently, I am developing a basic sanitizer for string input in Node (express): After looking at various plugins and libraries, I found that most of them are either too complex or heavy. Therefore, I made the decision to create some simple sanitizing fun ...

Running the Jcrop function multiple times within another function will not result in execution

When I click on the 'Edit A' link, a window opens where I can use Jcrop for editing. The process works smoothly for the first image. However, when I try to edit the second image using the 'Edit B' link, it keeps displaying the first ima ...

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

I am unable to access the properties of an undefined element, specifically the 'size' property in Next.js 13

I encountered a problem today while working with Next.js version 13.4 and backend integration. When using searchParams on the server side, I received an error message: "Cannot read properties of undefined (reading 'size')" while destructuring siz ...

Entering numbers using <input type="number"> does not restrict invalid inputs, while accessing "element.value" does not give me the ability to make corrections

According to the MDN documentation on the topic of <input type="number">: It is said that they have built-in validation to reject entries that are not numerical. But does this mean it will only reject non-numerical inputs when trying to ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Encountering a peculiar issue with including no-cors in the header while fetching JSON content in a React.js application

As someone who is relatively new to react and nodeJS, I am currently experimenting with pulling JSON data from my nodeJS webservices and displaying it in a react component. let url = "http://codepen.io/jobs.json"; let iterator = fetch(url); iterator ...

Interactive input field designed for modifying, adding, and removing data in MySQL

I am working on a project where I have a simple form. However, I need to dynamically change the form action from insert to update within the same page. Additionally, I also want to display the values on the same page. Within my code, I have set up the up ...

What is the most efficient way to update a particular item in an array within a React component's state while maintaining its conventional approach?

When working with React component state, I often struggle with manipulating a specific item in an array. Take this example: state={ menus:[ { id:1, title: 'something', 'subtitle': 'another something', switch ...

Blender models lose their texture when imported into Three.js

Currently, I am facing a challenge in exporting a model with texture from Blender to be used in Three.js. I am utilizing the Blender export to Three.js plugin for this purpose. https://i.sstatic.net/sLkKY.png (Red): This depicts the model within Blender ...

Issue with dynamic code detected by Sys.Application.add_init

I am facing a challenge with an older application that I recently took over ownership of. My efforts to successfully run it have been partially fruitful, as I am encountering some strange behavior that seems to be related to Internet Explorer 11. Interesti ...

Is your Firebase .push() function encountering errors when trying to update the database?

I am facing an issue with a component that checks if a user has already upvoted a post. The logic is such that if the user has upvoted a post before, they cannot upvote it again. However, if they haven't upvoted it yet, they should be able to do so. ...

Display additional tiles within a compact container

I'm attempting to replicate the user interface used by foursquare! Positioning the map slightly off center like they have . I've figured out how to do one part but struggling with the second part. Initially, I loaded the map in a small div (t ...

The intended functionality of clicking on an image is exclusively reserved for its immediate parent element

I have a feature on my website that displays an image gallery. When a user clicks on an image, it opens up the image in full screen similar to Facebook's theatre mode. I have written code so that when the user clicks anywhere in the container of the i ...

Can a function be called from outside its parent function?

I was pondering the possibility of calling a function from outside its parent function: var $element = $( '.element' ); function myFunction( element ) { var width; function onResize() { width = element.width(); } onResi ...

Tips for personalizing an angular-powered kendo notification component by adding a close button and setting a timer for automatic hiding

I am looking to enhance the angular-based kendo notification element by adding an auto-hiding feature and a close button. Here is what I have attempted so far: app-custom-toast.ts: it's a generic toast component. import { ChangeDetectorRef, Componen ...

Secure TypeScript Omit Utility for Ensuring Type Safety

I need to create a custom implementation of Lodash's _.omit function using plain TypeScript. The goal is for the omit function to return an object with specific properties removed, which are specified as parameters after the initial object parameter. ...