Ways to patiently await the completion of angular.foreach?

After angular.forEach completes execution, I need to set the bulkUpdateCheck flag to false.

function bulkUpdate(curritems) {
         
    $scope.bulkUpdateCheck = true;

    angular.forEach(curritems, function (item) {
        // multiple calls 
    });

    $scope.bulkUpdateCheck = false;
}

Answer №1

It is crucial that your loop finishes before setting bulkUpdateCheck to true.

The issue lies in the "multiple calls" you are making, which could be asynchronous. Therefore, everything inside your loops must conclude.

If there are async calls within your forEach, consider the following approach:

 async function bulkUpdate(curritems) {            
       
        $scope.bulkUpdateCheck = true;
        let multipleCalls = [] //this array will store all promises
         angular.forEach(curritems, function (item) {
               //modify this to suit the promise being used
               const promise = Promise.resolve(3);                 
               multipleCalls.push(promise)
         });
         await Promise.all(multipleCalls)
         $scope.bulkUpdateCheck = false;
    } 

Answer №2

To initiate a digest when it resolves, you can utilize the $q.all() function provided in AngularJS.

Create an array of promises for your $http requests using the Array#map() method and pass it to $q.all().

angular.module('app', [])
  .controller('main', ($scope, $q, $http, $timeout) => {
    const api_url = 'https://jsonplaceholder.typicode.com/todos/';
    const todoIds = [1, 3, 6, 9, 12];

    bulkUpdate(todoIds);

    $scope.todos = [];


    function bulkUpdate(curritems) {
      $scope.bulkUpdateCheck = true;
      // map arry of request promises
      const reqPromises = curritems.map(n => {
        return $http.get(api_url + n).then(res => res.data);
      })
      // runs when all requests resolved
      $q.all(reqPromises).then(data => {
        // extra delay for demo to see visual difference
        $timeout(() => {
          $scope.bulkUpdateCheck = false;
          $scope.todos = data;
          console.log(data)
        }, 1500)
      })
    }



  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="main">
  <div ng-if="bulkUpdateCheck">Loading...</div>

  <div ng-repeat="item in todos">
    <input type="checkbox" ng-checked="item.completed" /> {{item.title}}
  </div>
</div>

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

Alert: An invalid value of `false` was received for the non-boolean attribute `className`. To properly write this to the DOM, please provide a string instead: className="false" or use a different

While many have tried to address this issue before, none of their solutions seem to work for me... The error I am encountering is: If you want to write it to the DOM, pass a string instead: className="false" or className={value.toString()}. If ...

Tips for efficiently expanding NodeJS while running it through an Apache web server?

Currently, I have Apache Web Server running alongside NodeJS on the same system but on different ports. I am reverse proxying to connect and use them for various purposes. My concern is how to scale this architecture up to accommodate around 10 million u ...

JavaScript is causing performance issues in Selenium with Python

I am facing a challenge with web scraping a site that utilizes JavaScript/AJAX to load more content as you scroll down. My setup involves Python 3.7 and Selenium Chrome in headless mode. However, I've noticed that as the scraping process continues, th ...

A guide on incorporating the section tag in AngularJS to achieve a responsive design

Is it possible to implement AngularJS on a webpage with three sections and make it responsive by converting two sections into dropdown buttons? <body> <section id="main"> <section id="body"> // content in li elements ...

Reverting changes in an Angular directive

Initially, I created a directive that receives an object via bindToController for editing. Everything worked well until I needed to cancel an edit. To undo the changes, I had to create a duplicate of the original object, make changes to it, and then either ...

Using setTimeout within a ForEach loop does not adhere to the specified milliseconds for waiting

Although ForEach console.log's very fast, I am looking to introduce a delay of 8 seconds before logging the next item in Set. I experimented with setTimeout but it doesn't appear to output at the precise milliseconds specified. const completedIds ...

Risk Score Generating Form

As I work on a comprehensive form, there are 5 sections for users to mark if they qualify (using checkmarks). The form consists of approximately 50 questions in total. Each section carries different weights/points (e.g., Section 1 is worth 1 point each, ...

Angular JS time picker is the easiest and most user-friendly option for selecting the

Hello everyone, I'm looking for a straightforward timepicker popup solution for AngularJS. I've tried a few options like the timepickers found at http://embed.plnkr.co/2ReOvuuhtNNcgtmWycOt/ and , but ran into injection errors. Any suggestions ...

Error message: JSON.parse encountered an unexpected "<" token at the start of the JSON input

Currently, I am looping through an object and sending multiple requests to an API using the items in that object. These requests fetch data which is then stored in a database after parsing it with JSON.parse(). The parsed data is sent to a callback functio ...

Having trouble with Passport.js authentication not functioning properly

Setting up passport for the first time and opting for a single Google sign-in option. I've gone through the process of registering with Google APIs to get everything set up. However, when my app calls '/auth/google/', it fails without any re ...

Upon loading the page, a forward slash is automatically added to the end of the URL

My website has multiple pages of content, but I've noticed a strange issue with the URLs. When I navigate to example.com/guides, a forward slash is automatically added to the address bar, resulting in example.com/guides/. Surprisingly, the page still ...

Issues with HTML5 video playback have been encountered on Chrome and Internet Explorer after hosting the video on a server. The video is in the MOV file format

On our teamVideo.html page, we are incorporating the HTML5 video tag to showcase a video file in .mov format that was captured using an iPhone. <video preload="none"> <source src="video/v1.mov"> </video> When the teamVideo.html page is ...

Error: Unable to assign a value to the 'name' property of an undefined object after modifying input field data

I am currently working on developing a React application. The app includes a button labeled "Add" that, when clicked, adds multiple input fields to the screen. Each line of inputs also features a button marked "X" which allows users to remove that specific ...

Why does `window.location.reload()` only refresh the home page and not the other pages when using Angular?

After transitioning from the home page to the menu page, I expect the menu page to refresh automatically once. However, when implementing the code below, the home page is refreshed first before navigating to the menu page without an auto-refresh. 1)Initia ...

Troubleshooting issue with ng-selected functionality in Angular version 1.5.7

I am facing an issue with a select element in Angular 1.3.9 where the default selected data is set using ng-selected. However, after upgrading to Angular 1.5.7, the ng-selected functionality stops working and the default date is not being set. How can we ...

Is there a way to pause a timer set in setInterval with a click and then resume it with another click?

As a beginner in react, I am currently working on a react component that has multiple features. Users can input a random number, which will then be displayed on the page. Implementing a button with the text value 'start'. When the button is cli ...

Ways to showcase an item within additional items?

I'm struggling to properly display data in a table. My goal is to iterate through an object within another object inside an array and showcase the source, accountId, name, and sourceId in the table. https://i.sstatic.net/VVIuc.png <tbody clas ...

Finding the Port Number where the NodeJS server is actively listening

I am currently facing an issue retrieving the port number on which NodeJS is listening. I have saved the port number value in the app.js variable and attempted to access it in the index.js file. However, I keep getting an undefined value in the index.js fi ...

divs that are dynamically arranged and responsive, with text rotated at a 90-degree angle

I have been attempting to achieve a specific appearance. https://i.sstatic.net/i6Ylz.png However, the only way I have managed to accomplish it is with a transform (which seems to be causing an issue). I cannot seem to find any other methods for rotating ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...