Angular service that iterates through each $q.promise

Here's the function I am working with:

    this.getBenchmarkData = function () {
    var benchmarkData = [];
    var d = $q.defer();
    users.forEach(function(user){
        var dataArray = [];
        modules.forEach(function (module) {
            $http.get(api.getUrl('teamUserBenchmark', [user.user_id, module.id, user.team_id]))
                .success(function (response) {
                    response.forEach(function(result){
                        dataArray.push(result.score);
                    })
                });
        });

        benchmarkData.push(dataArray);

    });
    d.resolve(benchmarkData);

    return d.promise
}

The issue is that d.resolve(benchmarkData) runs before any actual data has been added to it.

I understand that this problem stems from the asynchronous $http task. However, I'm unsure about how to go about resolving it. Can someone provide guidance on the correct approach?

Answer №1

To properly resolve the promise, make sure to gather all promises in an array and then use $q.all to resolve the deferred promise.

Sample Code:

this.getData = function () {
var data = [];
var d = $q.defer(), promise = [];
users.forEach(function(user){
    var dataArray = [];
    modules.forEach(function (module) {
        var currentPromise = $http.get(api.getUrl('dataEndpoint', [user.user_id, module.id, user.team_id]))
            .success(function (response) {
                response.forEach(function(result){
                    dataArray.push(result.data);
                })
            });
        promise.push(currentPromise); //<-- Create promise array here
    });
});
$q.all(promise).then(function(){ 
   data.push(dataArray); // Add complete data
   d.resolve(data); // Resolve after all promises are completed
});


return d.promise

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

CKEditor Missing Plugin Icon for YouTube Video Embedding

After following the instructions on how to add a Youtube plugin in CKEditor and adding the code to config.js, I was disappointed to find that the youtube insert button did not show up on the toolbar. My next step was downloading and extracting the Youtube ...

HTML Button without Connection to Javascript

When attempting an HTML integration with GAS, the code provided seems to be generating a blank form upon clicking "Add" instead of functioning as expected: //GLOBALS let ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var lastRow = ss.getLa ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Is it possible to have numerous HTML files and directories in Phonegap/Cordova along with plugins?

As I transform my web app from HTML to Cordova for enhanced device functionality, including background audio and other features, I'm encountering some challenges. Due to the original structure of my application, which consists of multiple HTML files, ...

What is the best way to avoid the pipe symbol in jade formatting?

When working with jade, the pipe symbol (|) is utilized for displaying plain text. But what if you need to actually write it on the page? Is there a way to escape it in Jade? ...

Looping through ViewData strings and populating a form with their values

I am currently utilizing ASP.NET and MVC to work on a project where I need to take a list of strings and populate a form with them. The goal is for users to import account numbers, have the form prefilled with these numbers, and then submit the data. I&apo ...

Leveraging data within Gatsby to dynamically generate and display content

I am encountering a problem as a newcomer to Gatsby. In my EventsContainer, I have an UpcomingEvent component where I need to render specific data only when upcomingEvent is true. While I successfully utilized map for EventCard, I'm struggling to do t ...

What could be causing my angular-ui-tour to not detect the steps in my separate tour?

Utilizing angular-ui-tour to incorporate multiple tours within the same DOM for my project, specifically utilizing the detached tour option for this purpose. My relevant dependencies in this scenario are: angular 1.5.7 bootstrap ^3.3.6 angular-bootstra ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

Using AngularJS and JavaScript, set the Submit button to be enabled only when the email input is valid and a value is selected in

I'm trying to create a form that includes an email input field and a drop-down list sourced from a database array. Initially, the submit button is disabled when the form loads. My goal is to figure out how to activate the submit button only when the ...

Link the Material-ui ToggleButtonGroup with redux-form

I'm currently facing a challenge with connecting the material-ui ToggleButtonGroup to Redux form. The issue seems to be occurring in my code snippet below: <Field name='operator' component={FormToggleButtonGroup} > <ToggleButt ...

Using a function with a parameter as an argument in an event handler

Imagine you have the code snippet below: $('#from').focus(listExpand(1)); $('#to').focus(listExpand(3)); I am facing an issue as the code is not behaving as expected. I believe the problem lies in passing a function result instead of ...

Issue occurred when trying to load controllers during the migration process from AngularJS1 to Angular6

Currently, I am in the process of upgrading AngularJS1 components to Angular6. My strategy involves creating wrappers for all existing AngularJS1 components by extending "UpgradeComponent" and storing them under the folder "directive-wrappers". However, wh ...

Having trouble implementing connect-busboy in my Node.js application

Currently, I'm trying to implement image uploads in my node.js application using connect-busboy. Here's the code snippet I've written based on the reference guide https://www.npmjs.org/package/connect-busboy: router.post('/upload&apos ...

MongoDB issued an error notification stating: "The operation `disneys.insertOne()` has experienced a timeout after 10000 milliseconds."

I am currently in the process of developing a new API using MongoDB and Express, and I have come across the following issue: "Operation disneys.insertOne() buffering timed out after 10000ms." To test my API, I am using route.rest. However, I ...

JavaScript fails to effectively validate URLs

I have implemented the following validation for URLs: jQuery.validator.addMethod("urlValidatorJS", function (value, element) { var regExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{ ...

What is the process of choosing a language (English/French) within a pop-up?

<body style="text-align:center"> <h2>Popup</h2> <div class="popup" onclick="myFunction()">Interact with me to show/hide the popup! <span class="popuptext" id="myPopup">A Simple Popup!</span> </div> <script& ...

An error occurred during the bundling process in React Native

I recently started using react-native and encountered a perplexing error that I cannot quite figure out. My goal is to integrate a calendar library into my project: https://github.com/wix/react-native-calendars I have added the necessary dependency for t ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

Exceljs : 'An issue has been identified with certain content in the document named "file.xlsx"(...)'

I have encountered an issue with an xlsx file generated using Exceljs. While I have been creating csv files in my project without any problems, creating an xlsx file now poses an error. The xlsx file opens clean on Ubuntu/LibreOffice Calc, but there is an ...