Issue with passing multiple promises to $q.all function

Currently, I am attempting to iterate through an object and fetch data for each iteration from two separate service API functions. These functions return promises due to using the $http object, which means I must wait for the responses before populating my object.

This is my first time working with the $q AngularJS library and I'm uncertain if I'm using it correctly. It appears that I am not as expected results are not being returned, causing issues with my code.

Below is the snippet of my controller function:

$scope.returnTasksAndPayments = function() {
    var defer = $q.defer;
    var promisesTasks = [];
    var promisesPayments = [];

    for(var i in $scope.projects) {
        promisesTasks[i] = ProjectService.fetchTaskData($scope.projects[i].project_id);
        promisesPayments[i] = ProjectService.fetchPaymentsData($scope.projects[i].project_id);
    }

    $q.all(promisesTasks, promisesPayments).then(function(promiseArray) {
        console.log(promiseArray);
    });
};

Here are the related service functions:

this.fetchProjectsData = function(options) {
    return api().get("http://dashboards.blurgroup.dev/src/projectPayments/services/JSONdata.json", {
        order: options.order,
        page: options.page,
        page_size: options.page_size,
        status: options.status,
        search: options.search,
        assigned: options.assigned
    });
};

this.fetchTaskData = function(options) {
    return api().get("http://dashboards.blurgroup.dev/src/projectPayments/services/JSONdataTasks.json", {

    });
};

this.fetchPaymentsData = function(options) {
    return api().get("http://dashboards.blurgroup.dev/src/projectPayments/services/JSONdataPayments.json", {

    });
};

In essence, I am looping through $scope.projects, invoking the two functions for each iteration, storing them in separate promise objects, and then utilizing $q.all to ensure both promises are fulfilled.

The issue lies in the fact that the data stored in the 'promisesPayments' array within the $q.all function isn't being added to the promiseArray variable in the $q.all callback. If anyone can provide insight into where I may be making a mistake, I would greatly appreciate it. Thank you.

Answer №1

Here's a suggestion:

var allTasksPromises = $q.all(tasksPromises);
var allPaymentsPromises = $q.all(paymentsPromises);

$q.all([allTasksPromises, allPaymentsPromises]).then(function(result){
    //result[0] will hold tasksPromises information
    //result[1] will hold paymentsPromises information    
});

Answer №2

To efficiently handle the data, consider concatenating your two arrays into one large array and passing it to $q.all().

If you prefer separating the returned data, you can nest your resolves like this:

$q.all(promisesTasks).then(function(promiseTaskData) {
    console.log(promiseTaskData);
    $q.all(promisesPayments).then(function(promisePaymentsArray) {
        console.log(promisePaymentsArray);
    });
});

Remember that using

$q.all(promisesTasks, promisesPayments)
creates a nested array [[],[]], which is not compatible with $q.all()

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

Combining all CSS files into one and consolidating all JavaScript files into a single unified file

Whenever I need to add a new CSS or JS file, I always place it in the header section like this Add CSS files <link rel="stylesheet" href="<?php echo URL; ?>public/css/header.css" /> <link rel="stylesheet" href="<?php echo URL; ?> ...

Change this npm script into a gulp task

I have a script in npm that I would like to convert into a gulp task. "scripts": { "lint": "eslint .", "start": "npm run build:sdk && node .", "posttest": "npm run lint && nsp check", "build:sdk": "./node_modules/.bin/lb- ...

Generating numerous checkboxes dynamically

Seeking assistance with a jQuery function that dynamically generates or clones checkboxes. The challenge is to display the sub_item checkbox when the main_item checkbox is checked. For a demonstration, you can visit this DEMO Jquery $('#btnAdd' ...

I'm facing a challenge with discord.js where I can't seem to get multiple prefixes to work. Do you have any suggestions on how I can modify it to

As the title suggests, I've been experimenting with different versions of the code below. The current version can recognize firstPrefix but not secondPrefix. I simply want my discord bot to be able to identify both prefixes and split the Args accordin ...

Refreshing information in the MongoDB database

I found a file named Musicians.js that includes the following code snippet: exports.update = function(req, res) { var id = req.params.id; console.log("ID-->" + id); //I GET CORRECT ID HERE var updates = req.body; //It does not update any records ...

What are the ways to convert canvas animations into gif or webm formats?

I've written a function to capture each frame for the GIF, but I'm experiencing laggy output and crashes as the data increases. Any recommendations? function generateGifFromImages(imageList, frameRate, fileName, scaling) { gifshot.createGIF({ ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

Do we need to have the 'input type file' field as

I am currently working on a PHP form that includes mandatory fields for saving the data. For example: <td><input class="text_area required" type="text" name="new field" This form also has Javascript code with file upload functionality, which I ...

Updating HTML images in real-time using a combination of Flask and Ajax

I am facing a situation similar to the one discussed in this thread: Flask+AJAX+Jquery+JINJA to dynamically update HTML Table. However, I am struggling to adapt the solution to suit my specific requirements. My objective is to automatically update the imag ...

Passing a variable in an AngularJS $http.get() call to retrieve a specific section of a JSON data file

Currently, I am using json files to stub my $http.get() calls. I am trying to retrieve a specific subset of the json file in my angular controller. Despite looking at other solutions that recommend setting a params property in the Get call, it does not see ...

Strings that automatically adjust to fit the content from a JSON object

I have a JSON object with a long string that I want to display. The string looks like this: "String":"<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever si ...

Implementing a Div response within the actionPerformed method

I've spent hours working on this javascript/ajax code trying to get it to add a div response that was echoed by a php script. Any assistance with this would be greatly appreciated. <form id="form1" name="form1" method="post" enctype="multipart/for ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

The function I created is having trouble connecting to the controller.js file

My JavaScript controller file function ServicesCtrl($scope) { console.log("Greetings from ServicesCtrl"); $scope.message = "Hello!"; } The main HTML file <html> <head> <title>The Complete Web Development Stack</ti ...

Can the default Bootstrap classes in the ExtLib application layout control be modified?

I am currently using the responsive Bootstrap theme in combination with the application layout control in extlib, but I have been unable to locate any documentation on whether it is possible to modify the predefined Bootstrap classes. In the example below ...

Using cookies locally is smooth, but unfortunately they don't seem to function as expected on VPS

I am experiencing an issue with cookies when deploying my nodejs and angularjs 1.6.4 project from localhost to Digital Ocean droplet via Github. Although everything functions properly on localhost, the cookies do not work on the droplet. Any data saved to ...

Exploring the usage of slots in WebComponents without relying on shadow DOM

I am working on developing a WebComponent without utilizing ShadowDOM. So far, everything has been going smoothly. However, I now aim to create a component that wraps other components similar to how it is done in Angular with @ViewChild / @ViewChildren. (I ...

How can I retrieve the Id from a TextField in MUI when the select property is activated?

I am struggling to retrieve the id from the mui TextFiled element when the select property is activated. However, I am always getting an undefined value. Here is the code snippet: export default ({ onChangeSelect, input, label, options, ...

Using PHP code to pass a value to JavaScript

I have both PHP and JavaScript code on my page, and I need to retrieve a value from PHP into my JavaScript code. Below is my JavaScript code: <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Bread ...