Using Angular's promise queue to efficiently handle loading data

My approach with Angular's $q promise looks like this:

$scope.loadingData = true; // display loading spinner on the view 
var itemsToProcess = [....];

for(int i = 0; i < itemsToProcess.length; i++) {
    var itemToProcess = itemsToProcess[i];

    makeServiceCallThatReturnsPromise(itemToProcess)
        .then(function(response) {
                   processAndDisplayResponse(response);
         });
}

$loadingData = false; // hide loading spinner

One issue I am facing is that since the service call promises are queued, the loading indicator disappears before all the data is returned.

How can I ensure that the loading flag remains set until all promises are fulfilled?

Answer №1

Utilize the $q.all() method for handling multiple promises at once.

let arrayOfPromises=[];
for(let i=0; i<items.length; i++) {
    let item = items[i];

  arrayOfPromises.push(  serviceCallToReturnPromise(item)
        .then(function(response) {
                 //perform tasks here
         }));

}

$q.all(arrayOfPromises).then(function(){
  processAndRender(response);
})

Answer №2

The recommended method for achieving this is through the use of $q.all().

Answer №3

Utilizing $q.all(arrayOfPromises).then(successFunction(), failureFunction()).[catch] can be helpful in this scenario.

var completionStatus = false;

function processPromises() {
    var promiseList = [];
    angular.forEach(itemsArray, function(item, index) {
        var promise = createPromise(item);
        promiseList.push(promise);
    });
    $q.all(promiseList).then(onSuccess, onFailure);
}

function onSuccess(data) {
    completionStatus = true;
};

function onFailure(error) {
    completionStatus = false;
};

It is important to note that if one promise fails, the failureFunction will still be triggered even if other promises have succeeded. $q.all failure called

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

The React.js Mui Collapse component exclusively triggers animation during the transition while closing, without any animation when expanding

Whenever I implement the Collapse component from Mui library in my projects, I face an issue where the transition animation only works when closing the component (when in={false}). However, when opening the component, there is a delay before the animation ...

Event in Bootstrap modal fails to activate

I've been attempting to link some code to execute when my modal is opened. Despite successfully opening the modal, I am puzzled as to why my event fails to trigger. Below is the structure of my modal: <div id="details" class="modal fade" style="d ...

What is the best way to switch between three different menus and ensure that the last selected menu remains open when navigating to a new page

My knowledge of javascript, jquery, and php is pretty much non-existent, unfortunately. I only have a grasp on html and css at the moment. However, I will be starting school to learn these languages in the fall! The issue I am currently facing is creating ...

What's the process for changing this arrow function into a regular function?

Hello from a child component in Vue.js. I am facing an issue while trying to pass data from the parent via sensorData. The problem lies in the fact that the arrow function used for data below is causing the binding not to occur as expected. Can anyone gu ...

spinning camera around a globe with javascript and three.js

In my project, I am working on enabling a player to navigate in a first-person view on a planet using three.js and JavaScript. There are two key aspects I am focusing on: a) Implementing player movement around the planet, which involves two types of movem ...

Performing AJAX request when a link is clicked within a Wordpress website

I am looking for a way to initiate a PHP function in my Wordpress site when a link is clicked, rather than using a form submission. I have tried using an AJAX request but it doesn't seem to be working. Any suggestions would be greatly appreciated. Be ...

Fluctuating price depending on the selected choice

Hello, I am in the process of updating the price based on the selection made from the options. I am unsure whether to use JavaScript or Ajax for this task and how to go about it. Can someone please guide me? <tr> <td width="160">Price:</td ...

Send information back to the initial website following a sequence of alternating requests

I am facing a challenge with my website's structure: On the "Client side", I have HTML / CSS / JavaScript, and on the "Server side", I have PHP. When a user interacts with the client side by clicking a button, they are redirected to a page where a s ...

Transforming an HTML file into a Vue.js component

I'm working on a login.vue file and I need to incorporate styling along with the necessary js and css files. Unfortunately, I'm clueless about how to achieve this within the login.vue file. Below is a snippet from the html file: <!DOCTYPE ht ...

Remove text on the canvas without affecting the image

Is there a way to remove text from my canvas element without losing the background image of the canvas? I'm considering saving the Image source and reapplying it to the Canvas Element after using clearRect, but I'm unsure how to execute this sol ...

Retrieve JSON information using AngularJS

Here is the JSON file I'm working with: { "countries":[ { "country": "India", "cities" : [{ "name": "Bangalore", "rank": "40" }, { "name": "Mumbai", "rank": "32" }, ...

Finding the IST date time (YYYY-MM-DD HH:mm:ss) in a Node.js environment is a common requirement. Let's

I recently used the code below to retrieve the current time and date in IST: const x = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '') Output: 2020-09-01 17:49:48 However, I actually need to obtain the time in IST ...

Ways to vertically shift an element while scrolling, exclusively within its corresponding BS4 container

Inside a Bootstrap 4 container, I have a div box that I want to scroll along with the nested content as I am scrolling. However, I want this movement to be confined within the boundaries of the respective Bootstrap 4 container. Ideally, I would like it to ...

What is the most reliable database for handling daily data?

Currently, I am involved in a project that involves monitoring daily data for approximately 30 fictional companies. Each company is associated with a name, rank, and balance. I aim to track the rank and balance by storing the data daily. My main query re ...

There is a lack of definition for an HTML form element in JavaScript

Encountering an issue with a HTML form that has 4 text inputs, where submitting it to a Javascript function results in the first 3 inputs working correctly, but the fourth being undefined. Highlighted code snippet: The HTML section: <form action="inse ...

What strategies can be employed to mitigate the activation of the losing arm in a Promise.race?

My current task involves sending the same query to multiple identical endpoints (about five) across various Kubernetes clusters. The goal is to aggregate the results without any delays and report failures to the user while continuing with the process seaml ...

What steps should I take to implement user access control in my current AngularJS application?

I have developed a login authentication application using AngularJS, but now I want to transform it into a user access control app. Can anyone provide suggestions on how to achieve this? Any help in guiding me through the process of enhancing my app would ...

Recalling a hidden div in a flexbox arrangement

I am facing a challenge with hiding and displaying two aside divs to enable a fullscreen view of my central div main. The layout is created using flexbox to assign proportions, but when I try to redisplay the elements, it disrupts the original design. Belo ...

Utilize the angularJS filter to emphasize the search text within the search results

I have a search box that filters results displayed on the screen. I am using a filter called 'startWith' for this purpose. Now, I need to implement a feature where the search text is highlighted among the search results in angularJS. For example ...

Utilize jQuery to run a script once everything is prepared and loaded

My website utilizes ajax technology, and within the ajax page, there is a piece of javascript code that needs to run only after the entire ajax page has loaded. I have attempted to use the following: $( '#ajaxdiv' ).load(function() { } However ...