Running a command once the forEach loop is completed in Angular

Within the HTML, I have a function that is triggered by an ng-click:

vm.items = [];
vm.moveItems = function() {
    angular.forEach(vm.items,
        function (item) {
            $http({
                method: 'PUT',
                url: '/api/item_move/' + item.id}
            }).then(function(response) {
                Toast.success("Successfully moved item " + item.id);
                vm.reload();
            }, function (error) {
                Toast.error("Failed to move item " + item.id, error);
            });
    });
};

The issue at hand is that the vm.reload() function is being called after each successful response. Ideally, it should be executed only once after the entire forEach loop has finished processing. As I am new to asynchronous programming in JavaScript, I would like to learn about the most commonly used methods to address this problem.

Answer №1

Organize an array to hold all the promises generated from your HTTP requests. When ready, invoke the Promise.all() method to handle actions once all promises are fulfilled.

vm.items = [];
vm.moveItems = function() {
    var promises = [];
    angular.forEach(vm.items,
        function (item) {
            promises.push($http({
                method: 'PUT',
                url: '/api/item_move/' + item.id}
            }));
    });
    Promise.all(promises)
        .then(function() {
            vm.reload();
        });
};

Update: For AngularJS users, consider using $q.all() as well.

Answer №2

Here is a possible solution:


const itemsList = [];
const updateItems = () => {
    let index = 0;
    itemsList.forEach(item => {
        fetch(`/api/update_item/${item.id}`, { method: 'PUT' })
            .then(response => {
                if (response.ok) {
                    console.log(`Item ${item.id} successfully updated`);
                }
                index++;
                if (index === itemsList.length) {
                    refreshPage();
                }
            })
            .catch(error => {
                console.error(`Failed to update item ${item.id}`, error);
                index++;
                if (index === itemsList.length) {
                    refreshPage();
                }
            });
    });
};

Answer №3

Answer:

vm.items = [];

vm.moveItems = function() {
    var tasks = [];

    angular.forEach(vm.items , function(item) {

        var task = $http({
            method: 'PUT',
            url: '/api/item_move/' + item.id}
        }).then(function(response) {
            Toast.success("Item " + item.id + " has been successfully moved");
        }, function (error) {
            Toast.error("Failed to move item " + item.id, error);
        });

        tasks.push(task);

   });

   $q.all(tasks).then(function() { vm.reload() })
});

Answer №4

Relocate the call to vm.reload() outside of the forEach loop:

vm.items = [];
vm.moveItems = function() {
  this._$timeout(() => {

    angular.forEach(vm.items,
      function (item) {
        $http({
          method: 'PUT',
          url: '/api/item_move/' + item.id}
        }).then(function(response) {
          Toast.success("Successfully moved item " + item.id);
        }, function (error) {
          Toast.error("Failed to move item " + item.id, error);
        });
    });

  });

  vm.reload();
};

After adding $timeout, the function should allow enough time for the foreach loop to complete.

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

Interactive window allowing the user to closely examine code

Hey guys, I need your help with something Is there a way (PHP / jQuery) that allows me to zoom in on my code? Similar to how lightbox works for images. I specifically want to zoom in on dynamic code while using Yii's CListView. I'm thinking of ...

Implement a feature to dynamically load data as the user scrolls up, similar to the

I am in the process of creating a messaging platform and I am looking to implement a functionality where chat history is displayed upon scrolling up, similar to Facebook's chat system. Can anyone offer assistance with this task? ...

Tips for combining all included files into one with Babel

My current project involves the use of Babel. Within my server.js file, I have the following line of code: import schema from "./data/schema"; The issue arises because data/schema.js is written in ES2015 syntax. After attempting to compile my server.js ...

The Protractor allScriptsTimeout feature appears to be ineffective when attempting to load an AngularJS application

My scripts are experiencing timeouts because my page occasionally takes more than 30 seconds to load. After researching online, I tried using various options such as getPageTimeout, allScriptsTimeout, and defaultTimeoutInterval in JasminNodeOpts, but none ...

Having trouble with @babel/plugin-proposal-optional-chaining in Vue.js <script> tag

While working on my vue/vuetify project and attempting to implement optional chaining, I consistently run into an error: ./src/App.vue?vue&type=script&lang=ts& (./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??v ...

What is the correct way to utilize the karma-ng-html2js-preprocessor?

I'm working on a directive called stat24hour: angular .module('app') .directive('stat24hour', stat24hour); function stat24hour(req) { var directive = { link: link, template: 'scripts/widgets/templ ...

angular 2 text box clearing functionality appears to be malfunctioning

I am currently working on implementing a reusable search box in Angular 2. Although the code is relatively basic, I am new to Angular 2 but have some experience with Angular 1. I am facing an issue where the value is not clearing when the text box is foc ...

Unlimited digest loop in Angular.js caused by nested ng-repeat and filter

In my AngularJS project, I have developed a custom filter that categorizes elements by type and performs a search for multiple search terms across all attributes of devices. angular.module('abc').filter('searchFor', function(){ return ...

What is the best way to retrieve a single document from MongoDB by using the URL ID parameter in JavaScript?

I'm currently working on a movie app project and have defined my movie Schema as follows: const movieSchema = new mongoose.Schema({ name: { type: String, required: true }, genre: { type: String, required: tr ...

Troubleshooting angular service jasmine test - unable to locate $http service

As I followed the tutorial at , I encountered an issue with the jasmine test provided. Despite simplifying the test to its core, it still fails to pass. Could someone point out where I might be going wrong? The service being tested is: var appServices = ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

Try utilizing a previous iteration of the generator-angular-fullstack

Is there a way to generate a project with generator-angular-fullstack without using ECMAScript 6? If not, do you have any alternative solutions for creating a project with Angular, Node, and MySQL? Thank you. ...

Steps to automatically populate the dropdown upon page load

Hello, I have a question regarding setting a value to a dropdown list in JavaScript. Currently, I am trying to execute this function during the onload event of the body tag. However, I am facing issues with setting the value. Below is the code: function s ...

Contrast between v-for arrangements

Would anyone be able to clarify the distinction between these two v-for structures? <li v-for="item in items" :key="item"> </li> and <li v-for="(item, i) in items" :key="i"> </li> ...

CSS to target every second visible tr element using the :nth-child(2n)

My table has a unique appearance (shown below) thanks to the application of CSS nth-child(2n). tr:nth-child(2n) {background-color: #f0f3f5;} https://i.sstatic.net/1AnDi.png I made some elements hidden on the vID, ID, and MO_Sub tr. <tr style="displa ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

Unexpected website icon shows up in my Node.js project

As a newcomer to working with the backend of Node.js, I'm facing an issue while trying to integrate favicons into my project using RealFaviconGenerator. Despite following the instructions provided, the favicons are not showing up on either my developm ...

Swapping out a code snippet within an HTML document using JavaScript

As a new member of this community, I present to you my very first problem that needs solving. It might be a piece of cake for some of you, but for me, it's proving to be quite tricky. The task at hand involves replacing or removing a string to make ev ...

Ways to check for child items in a JSON object

My Angular-built menu uses JSON and spans up to 3 levels deep. Some items have no children, while others go further down the hierarchy. I'm trying to determine if a selected subcategory has child elements in order to hide a button. Each time a subcat ...

Automatically submitting a form in React.js based on certain conditions being met

Does anyone have experience with React login and register form buttons that trigger Redux actions? I'm facing an issue where both actions are being dispatched at the same time when certain conditions are met. Here is my code snippet: const LoginPage ...