Executing multiple calls with Angular's $http service and then resolving them within a loop using underscore

I am facing an issue while trying to fetch multiple data from $http inside _.each function and display the combined data in $scope.tasksData.

The problem I encountered is that _.each is being executed later, causing it to return null first. Can someone please provide guidance on how to resolve this issue?

Thank you

var tasksList, processingStageId;

var apiURL = "http://localhost:9080/caseDetails/" + $stateParams.caseId + "?_=1461046349867";



var stagesList = $http.get(apiURL).then(function(resdata, status, headers, config) {

return resdata;

}).then(function(stagesData) {

stageId = stagesData.data.childStages;
var allTasksData = [];
var self = this;

_.each(stageId, function(item) {
    var stagesApiURL = "http://localhost:9080/stageDetails/" + item.stage.stageId;

    $http.get(stagesApiURL).then(function(taskData, status, headers, config) {
        //_.extend(allTasksData, taskData.data);            
        allTasksData.push(taskData.data);

    });
});

return allTasksData;

}).then(function(allTasksData) {
console.log("Hello");

_.each(allTasksData, function(data) {
    $scope.tasksData.concat(data);
});
});

Answer №1

To retrieve data after resolving all requests, you can use the $q.all([prom, prom, prom]) method.

.then(function(stagesData){
    var stageId = stagesData.data.childStages;
    var tasks = [];

    _.each(stageId, function(item){
        var stagesApiURL = "http://localhost:9080/stageDetails/" + item.stage.stageId;
        var req = $http.get(stagesApiURL).then(function(taskData, status, headers, config){            
            return taskData.data;
        });
        tasks.push(req);
    });

    //Combine all promise requests and resolve when all requests are resolved
    return $q.all(tasks);

})
/**
 * allTasksData - [taskData.data, taskData.data , ...]
 */
.then(function(allTasksData){
  ...
});

Answer №2

To solve this issue, ensure you include the $q service and utilize the $q.all function.

var stagesList = $http.get(apiURL).then(function(resdata, status, headers, config) {
  return resdata;
})
.then(function(stagesData) {
  stageId = stagesData.data.childStages;

  var self = this;

  return $q.all(
    _.map(stageId, function(item) {
      var stagesApiURL = "http://localhost:9080/stageDetails/" + item.stage.stageId;

      return $http.get(stagesApiURL).then(function(taskData, status, headers, config) {
          return taskData.data;
      });
    })
  );
})
.then(function(allTasksData) {
  console.log("Hello");

  _.each(allTasksData, function(data) {
      $scope.tasksData.concat(data);
  });
});

A brief explanation: we opt for using map instead of each to create an array of promises. Subsequently, we pass this array of promises to the $q.all function which generates a new promise containing an array of taskData.data as its parameter.

Answer №3

$q.all() is a helpful tool at your disposal.

As stated in the documentation:

It combines multiple promises into one promise that will only be resolved once all input promises are resolved.

By registering all your calls and waiting for them to resolve, you can then proceed with processing your data as needed.

Check out this example fiddle (not created by me) to see how it operates.

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

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

Is it possible to use both material-ui@next and the previous version concurrently?

I need some advice on a project I am working on that utilizes material-ui@next (v1). While I appreciate the new features in the latest autocomplete, I find it too complex for my needs. Instead, I would like to revert back to the older version of the autoco ...

Exploring categories with AngularJS filtering

I dived into AngularJS today and embarked on creating a straightforward app featuring categories with items. The app showcases categories in a sidebar (aside.navigation) and displays all the items in the main view. My initial idea was to load all the item ...

Is it possible for JavaScript to detect elements or scripts within a hidden element using display="none"?

Is it possible for scripts to locate elements that have been hidden in the DOM by setting their attribute to display="none"? ...

Looping through arrays within objects using NgFor in Angular 2/JavaScript

I have a custom object with data that I am iterating through using ngFor. Within this object, there is an array component that I also want to iterate through in a <li></li>. Currently, the output appears as one complete string within each < ...

What is the process for adding a highlighted area beneath a curve on a high chart?

I am working on creating a high chart with Angular 4 and I have a specific requirement to highlight certain portions of the Highchart. For example, in the image: In the image above, if a data point value drops below a certain limit (such as 0), it shoul ...

Tips for validating a receipt in an In-App purchase within an Ionic1 or Ionic2 application on iOS

Currently, I am working on integrating InApp purchases into an iOS app built with Ionic. However, I am facing difficulties in validating the receipt. Despite successfully obtaining the transaction ID and receipt post-purchase. ...

What methods do developers employ to establish connections between pages in AngularJs?

As a new AngularJS developer, I have a good grasp on concepts like SPA and Components. However, one area that still confuses me is how to efficiently redirect users to different pages within an Angular app. I am seeking advice on the best approach for seam ...

HOC that can be used with many different components

My Higher-Order Component is currently designed to accept a single component, but I want to modify it to handle multiple components dynamically. Here's the current implementation: let VerticalSlider = (Component) => { return (props) => ( ...

Implementing the decrement functionality within an onclick event handler for a variable

Can someone assist me with this issue? I am trying to use a variable ID in HTML to call a function on a JavaScript page. For example: (Minus button not functioning) <button class="minus-button quantity-button button" type="button" name="subtract" onc ...

Encountering a malfunction in executing the AngularJS controller file

In the project run with http-server and node.js, the angular controller is unable to connect with index.html. classifieds.js (function() { "use strict"; angular .module("ngClassifieds") .controller("ClassifiedsCtrl", ['$scope', ...

Position a div relative to another div with a static position

I am attempting to create a site that is fullscreen and responsive, but I am having issues with elements in the container overflowing on smaller screens, causing it to not be 100% as desired. I have tried using: top:100%; position:relative; width:100%; he ...

The FormData() object in Django backend is consistently found to be void of any data

I am currently experimenting with uploading an HTML form through AJAX using pure JavaScript, without jQuery. The form is put together in my template by combining three components: the CSRF token, a ModelForm, and a regular Django form (forms.Form). The vis ...

Error: Module not located - Unable to resolve 'crypto'

Upon running ng serve, I encountered a list of errors that need to be addressed. Here is my package JSON configuration: { "name": "ProName", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "tes ...

When it comes to utilizing jQuery for the mobile view, how many jQuery libraries are recommended for optimal performance?

I'm currently constructing a website using ROR, and for the mobile view, I've implemented the mobile_fu gem. The designer provided me with a design for the mobile view that includes various jQuery sliders, players, image sliders, drop-down menus ...

Retrieve JSON data from PHP using D3.request

Looking to extract data from an SQL database using PHP and then convert it into JSON format with the "echo json_encode($array);" function. I have a requirement to create a graph using D3.js, which means I need to transfer this JSON data from PHP. Can anyo ...

How can I open the Ion-datetime view for the current year without allowing the selection of a specific day?

I am currently troubleshooting an issue with an Ionic date-time picker component. Upon opening the datepicker, it defaults to showing May 2021. As I scroll to the present date, I notice a circle highlighting today's date indicating that it selects th ...

`problem with moment.js incorrectly identifying the day of a given date`

I'm currently working with a field that has the value 03-01-2020, which is in the DD-MM-YYYY date format. However, when I apply the code moment.utc(document.getElementById('date').value, "DD-MM-YYYY HH:mm:ss").toDate(), I noticed that the re ...

preserving the factory variable when reloading the page

I am faced with a challenge in my AngularJS website where I have two views - one for a filtered list of posts and another for a specific post. Each view has its own controller, and I need to pass the specified category and page information to the post-spec ...

I'm encountering an issue with this error message: "Warning: Each item in a list must be assigned a unique 'key' prop."

I encountered an error message... Warning: Each child in a list should have a unique "key" prop. I'm puzzled about this because I believe I have assigned a unique key for my map. All the resources I've checked regarding this warning are relat ...