Leveraging AngularJS's $q.all method

After working with multiple asynchronous calls, I successfully retrieved the desired results. However, upon attempting to utilize the arrays where I stored these results, numerous issues surfaced. Upon investigation, it seems that using $q.all is the solution, a concept that I have not used previously. Although I attempted to comprehend its usage by reading the documentation, I still struggled to determine where exactly it should be implemented in my code. Below is the snippet of code in question:


FT.getFT().then(function(result) {
    if (result.data.success) {
        for (var i = 0; i < result.data.ftListe.length; i++) {
            Compte.getComptesbyId(result.data.ftListe[i].collaborateurid).then(function(result) {
                lecollaborateur.push(result.data.col);
            });

            Tache.getTachebyId(result.data.ftListe[i].tacheid).then(function(result) {
                Projet.getProjetbyId(result.data.tachelistes.projet_id).then(function(result) {
                    projets.push(result.data.projetsListe);
                });
                task.push(result.data.tachelistes);
            });
        }
        $scope.ftListe = result.data.ftListe;
        $scope.task = task;
        $scope.lecollaborateur = lecollaborateur;
        $scope.projets = projets;
        console.log(result.data.message);
    } else {
        console.log(result.data.message);
    }

});

Answer №1

Let me demonstrate how $q.all() functions and provide an example for one of your promises. It will then be your responsibility to refactor all your code accordingly. I can even maintain variable names in French if you prefer :)

$q.all() enables you to resolve an array of promises that you pass as arguments to all(). The result of the promise will be an array where the elements correspond to the results of your promises.

In your scenario, within your main result, create an array of promises like this:

FT.getFT().then(function (result) {       
  if(result.data.success) {   
    var comptesPromises = [];

Instead of resolving promises within your loop, simply add all the relevant promises to this array, as shown below:

comptesPromises.push(Compte.getComptesbyId(result.data.ftListe[i].collaborateurid));

After the loop, resolve all the promises and assign the returning values to your model:

$q.all(comptesPromises).then(function(comptes) {
  comptes.forEach(function(el) {
    lecollaborateur.push(el.data.col);
  });
});

Make sure to inject $q for it to work properly.

I trust this guidance proves beneficial.

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

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

What causes my TypeScript to occasionally return an instance and other times return a class?

I've been developing an app to enhance my understanding of TypeScript. It functions perfectly in Chrome, however, I encounter a problem when running it in Edge. The issue lies within this method: set position(pos: Point) { const diffAsPoint ...

Convert an array of image objects into a video file

My task involves taking an array filled with image objects and encoding it into a movie project. While I have a Java server available for use if necessary, my preference is to handle this client-side using JavaScript. ...

Utilize the same controller and view for both searching and non-searching functionality within Angular

Currently, I am developing an Angular application that consists of a single controller and view. I am facing the challenge of wanting to display the same view with or without a search field, based on user preference. My idea is to pass an extra parameter ...

Node Express - Securely storing and accessing authentication tokens

I have set up an Express application and I need guidance on how to securely store tokens. After authenticating a user account, I receive an access token from an OAuth 2 server, which I then need to use for subsequent API requests. To protect the token va ...

Get the specific URL path from the designated <input type="file"> location

I recently encountered an issue with retrieving the file path of a selected file. I used the normal file type and attempted to use the .val() function, but it only returned the file name and not the full location of where the file is stored on my local mac ...

In React, I am currently working on implementing a feature that will allow the scene camera to move as the user scrolls

I'm currently working on incorporating a feature to enable movement of the scene camera when scrolling in React. However, as I am relatively new to using this library, I am unsure which implementation approach would be most suitable for achieving this ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

What does the $value property in angularfire refer to?

Having some trouble retrieving a value from my firebase using angularjs and angularfire. Here is the code snippet from my controller: $scope.componentStatus = syncData("components/-JI_JgHxm0TEUEVjADJn/status"); console.log($scope.componentStatus); After ...

Retrieving registered components dynamically in Vue.js

Check out my scenario on jsBin In my setup, I have a selector <component :is="selectedComponent"></component>, along with a <select v-model="currentComponent">...</select> that allows me to choose which one is displayed. Currently ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

Utilizing Javascript or XUL windows without the use of iframes offer

I'm in the process of creating a multitab website for my bookmarks, but I've run into some issues. Here is the JavaScript version of what I'm trying to achieve: Unfortunately, there are obstacles with this method. The websites in the tabs ...

What is the best way to update state for changing colors?

I have a specific condition that requires setting the state properly. However, when I attempt to do so using setColor within the if method, an error occurs - "Too many re-renders. React limits the number of renders to prevent an infinite loop." State: con ...

Error 500: Issue with JQuery AJAX File Upload

Hey there, I'm facing an issue with doing a file upload using JQuery's AJAX feature as I keep getting the error 500. $(function() { $( 'form' ).submit ( function() { $.ajax({ type: &a ...

Trigger a function with AngularJS when the page loads

I'm currently studying AngularJS. I have a set of article tags and want to display each article page without refreshing the page when a button is clicked. This website consists of only one page. The issue I am facing is that despite trying to call myF ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Is it possible to nest enums within enums in TypeScript programming?

enum TYPES { CODE = 1, TEXT, IMAGE, VIDEO } enum ALL_TYPES { CODE = 1, TEXT, IMAGE, VIDEO, NONE } Is there a way to incorporate the TYPES enum into the ALL_TYPES enum? ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Attempting to collapse the offcanvas menu in React Bootstrap by clicking on a link

Currently, I am utilizing a mix of React Bootstrap and React to develop a single-page application. In an attempt to make the Offcanvas menu close when clicking a link, I have experimented with various approaches. One method involved creating an inline scri ...