What is the best way to run a function once all resources have been resolved?

Is there a way to delay the execution of a function until all my resources have resolved successfully? I want to parse through the log array only after all the $resources have resolved and then push a single success notification to the UI instead of multiple notifications for each success.

The code below is inspired by this question on Stack Overflow: angular -- accessing data of multiple http calls - how to resolve the promises. Even though $scope.promises is empty because item.$save() doesn't return anything, you can see that I am trying to add the unresolved promise to the promises array.

$scope.save = function () {
  $scope.promises = [];
  $scope.log = [];

  angular.forEach($scope.menuItems, function(item) {
    $scope.promises.push(item.$save(function(menu){
      debugger;                            // execution gets here 2nd
      console.debug("success");
      $scope.log.push(msg: 'success');
    }));
   }, this);

  $q.all($scope.promises).then(function() {
    debugger;                              // execution gets here 1st
    console.debug("all promises resolved");
  });
};

Answer №1

When working with the $save function that does not return a promise, an intermediate one is required:

  angular.forEach($scope.menuItems, function(item) {
    var d = $q.defer();   // <--- creating an intermediate promise
    item.$save(
      function(menu){
        debugger;
        console.debug("success");
        $scope.log.push(msg: 'success');
        d.resolve(menu);  // <--- resolving it, optionally with a value
      },
      function(error){
        d.reject(error);  // <--- rejecting it if there's an error
      }
    );
    $scope.promises.push(d.promise);
   }, this);

It's important to remember to clear the array of promises to avoid accumulating garbage:

$q.all($scope.promises).then(...).always(function() {
    $scope.promises = null;
});

If $scope.promises is not needed in the view, it can simply be declared as a var instead of being stored in the scope.

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

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

The Oscillator node in the Web Audio API is unable to be started more than once due to an error

Every time I attempt to start, stop, and then start my oscillator again, I encounter the following error message: Uncaught InvalidStateError: Failed to execute 'start' on 'OscillatorNode': cannot call start more than once. Although usi ...

Creating a form with multiple checkboxes using Material-UI components where only a single checkbox can be selected

Creating a simple form using Material-UI with checkboxes to select one option and push data to the backend on submit is the goal. The Form component structure includes: multiple options represented by checkboxes only one checkbox can be selected at a time ...

Generating a dynamic method for uploading multiple files

Is there a way to dynamically generate multiple upload forms upon clicking a button? I currently have code that allows for uploading one file, but I would like to be able to add additional forms for each file. In other words, if I need to upload 7 files, I ...

How to retrieve a single value from a collection document in Meteor

I'm in the process of extracting a specific value from a Meteor collection document to incorporate it into a three.js setting. My goal is to generate a three.js object that makes use of information stored in the database, which remains constant at thi ...

What is the best way to parse a JSON file and create a dynamic webpage using jQuery with the data from the

As someone who is new to working with Node.js and JSON, I am encountering some issues when trying to extract data from a JSON file. Below is the code that I have written: 'use strict'; const fs = require('fs'); let questsRawData = fs ...

What is the issue with the character set?

Attempting to send request data from JavaScript to Java using JSON format. In JavaScript, the request body appears as: { "id": "3", "name": "Chicken pasta", "description": "Lets make chicken pasta", "category": "Unassigned", "favorite" ...

Is there a reason why the slide up feature is not working when I include the ul tag?

I need help with a jQuery code that will pull up/slide up an Html "p" tag when my page finishes loading. This snippet of jQuery code seems to be working fine: $(function () { $('.graybgc').slideUp(0); }); This is the HTML structure: <p ...

Is there a conventional method for implementing role-based access control for files in Angular?

I have built 4 projects in Angular that grant access to different roles. The dashboard consists of various content pages, with the initial page being the dashboard when a user logs in. The content displayed on the dashboard is determined by the logged-in ...

Is my Bootstrap malfunctioning? The grid system seems to be malfunctioning

My very first question here is quite simple. I have a script that creates rows with dynamic content by appending 4 boxes (columns) in one row and then appending the row to the container. After completing this process, it appends the container to the main c ...

Generating a new array based on the keys found in a collection of objects

My array structure is quite complex with multiple objects containing different properties. let arr = [ { id: 1, name: "tony", hatColor: "blue" }, { id: 2, name: "larry", hatColor: "red" }, { id: 3, name ...

Issues with Angular JS and Ionic Controller functionality not functioning correctly

I am having an issue where my controller in controller.js is not being called when I click on a button with ng-click in index.html. Any assistance would be greatly appreciated. My technology stack includes AngularJS 1 and the Ionic framework. Below are th ...

What steps should I take to retrieve a value from a Headless-UI component?

I have integrated a Listbox component from Headless-UI in my React project. The Listbox is contained within its own React component, which I then include in a settings form. How can I extract the selected value from the Listbox component and save it to th ...

Searching for the identification of the Object name or id that has been clicked within a Canvas Element

Within a <canvas> element, I have incorporated two images. var ctx = document.getElementById('canvas').getContext('2d'); var img1 = new Image(); img1.src = 'cloud.jpg'; img1.name = "Image 1"; img1.onload = function() { ...

"Embedding a Highcharts web chart within a pop-up modal window

I am looking to incorporate a Highcharts web chart onto a specific part of a Bootstrap modal, while ensuring the size remains dynamic along with the modal itself. Here's what I have attempted so far: Sample HTML code: <td><a href="#">${ ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

Refresh the component data according to the vuex state

In order to streamline my workflow, I am developing a single admin panel that will be used for managing multiple web shops. To ensure that I can keep track of which website I am currently working on, I have implemented a website object in my vuex state. Th ...

establish connections within dynamic data table entries

As a newcomer to Javascript, I've been struggling with a particular question for some time now. The challenge at hand involves a dynamic jQuery table where I aim to hyperlink one row of the table data to a .php page in order to perform certain querie ...

The Art of Using Ajax and jQuery in Joomla

Hello! I am currently facing an issue with the custom pagination for a Joomla component. I am attempting to create a list of user articles, displaying 3 posts per page without refreshing the webpage. After hours of searching for a solution, I decided to i ...