When working with AngularJS, I noticed that the service function within a loop is only executed after all iterations have been completed

Controller Page

    $scope.page = {
        '1' : "small",
        '2' : "large",
        '3': "medium"
    };      
    $scope.form.appraisal_id = "abc123";
    $scope.form.user_id = "efg123";
    for(var prop in $scope.page){
        $scope.form.question_id = prop;
        $scope.form.answer = $scope.page[prop]
        console.log($scope.form);
        appraisalService.saveForm($scope.form,function(result){
          $scope.sent=result
          console.log($scope.sent)
          });
};


My Result

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "1", answer: "small"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "2", answer: "large"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "3", answer: "medium"}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3, answer: "medium"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3, answer: "medium"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3, answer: "medium"…}

Expecting output

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "1", answer: "small"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "2", answer: "large"}

Object {appraisal_id: "abc123", user_id: "efg123", question_id: "3", answer: "medium"}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 1, answer: "small"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 2, answer: "large"…}

Resource {__v: 0, appraisal_id: "abc123", user_id: "efg123", question_id: 3,answer: "medium"…}

Answer №1

Consider using $q.

var promises = [];

for(var property in $scope.page) {
    $scope.form.question_id = property;
    $scope.form.answer = $scope.page[property]

    promises.push(appraisalService.saveForm($scope.form, function(result){
      return result;
    }));
}

$q.all(promises).then(function(result) {
  console.log(result);
});

The asynchronous nature of your appraisalService call means that the loop completes before any async calls finish, resulting in only catching the last call.

To address this, you can push each promise into an array and utilize $q.all to wait for all promises to resolve before logging the results.

If you are unfamiliar with $q, it is a part of Angular by default. Simply inject it as needed.

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

Custom attribute in ReactJS component - I am not defined in my custom attribute in React component

I am currently working with ReactJS and I am facing an issue regarding accessing a custom attribute -name- of my ReactJS component. Despite trying to use e.target.name, it keeps returning "undefined" on my console. I cannot seem to figure out why this is ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Failing to utilize callback functions results in forgetting information

I am facing an issue with my code where changes in the parent component trigger a re-render of the child element. The Menu component is supposed to appear on right-click on top of the placeholder tag, but when it does, the entire parent component flicker ...

Utilize jQuery to manipulate a subset of an array, resulting in the creation of a new array through the use of

I have a string formatted like this: ItemName1:Rate1:Tax1_ItemName2:Rate2:Tax2:_ItemName3:Rate3:Tax3_ItemName4:Rate4:Tax4 (and so on, up to item 25). My task is to take an index provided by the user (for example, 2), retrieve the item at that index when ...

Tips on leveraging dynamic queries in your REST API usage

As a new Javascript learner, I am experimenting with creating a basic rest api using node.js. Currently, I have set up a database called testDb and a table named testMeasurement in influxdb. The testMeasurement table consists of the columns DateOfBirth, ID ...

Exploring the Battle between LocalStorage and Redis for Front-end and NodeJS Development

Which approach is better for storing common user information like username and image: using localStorage or implementing Redis caching with NodeJs on the front-end? ...

The background image fails to load in ReactJS application

Usually, I have no trouble finding solutions to my problems, but this time I'm really stuck - and I apologize in advance if my question seems silly or trivial. I am currently working on a simple React app where I need to set a background image for th ...

Strategies for resolving the module not found error: Unable to locate '@mui/icons-material/Adb'?

I installed material-ui core using the command below: npm i @material-ui/core However, when running my reactjs code afterwards, I encountered this error message: Module not found: Can't resolve '@mui/icons-material/Adb' Can someone pleas ...

Is there a way to determine if a browser's network activity is inactive?

Within an angularJS application, a noticeable delay can be experienced between the user and the server (potentially due to limited bandwidth), resulting in a wait time of approximately 2-500ms when loading a new page. I am considering implementing a metho ...

Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from (with a slight change - no deviceready listener, code inside ionicPlatform.ready listener) Below is the code snippet: angular.module('myApp', [& ...

What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format: queryObj = {}; // main object passed to mongodb for queries The code snippet below is causing an error: queryObj[inObj.row]['$ ...

Modify the background color of a specific bar across multiple charts when hovering or clicking - utilizing chart.js

I have multiple chart.js canvas elements on a webpage. The goal is to be able to quickly identify and highlight the same bar value across all the charts. For example, when I hover over a bar called "Thu" on the first chart, I want to automatically search f ...

Is there a way for me to utilize the imported data from one component in the context API using an arrow function?

I am trying to utilize placeInfo, reviews, detailsInfo, news from a data file. Instead of using value='hello', I am unsure if I can directly use it like this: value={placeInfo, reviews, detailsInfo, news}, as it is producing an error. Should I st ...

Firebase authentication encountered an error due to a network request failure

Utilizing firebase Hosting to host my website, I am encountering a persistent error when attempting to login using email/password. This is the JavaScript code that I am using: window.onload = () => initApp(); //Initialize screen function initApp(){ ...

When you print document.getElementById('idname').value, it only displays [object HTMLInputElement]

Currently, I have a Tamper-monkey script in place that is designed to scrape specific text from a single page. The script's job is to extract the values of three buttons named pick_0, pick_1, and pick_2 from the page and display them in a designated b ...

When utilizing ui-router, the root url will automatically redirect to a state with an empty url

My parent state has a URL mapped for '/' and when I visit the root, like this example: http://localhost:8081/sin/TPW/, it automatically redirects me to a child state with an empty URL. I'm puzzled as to why this specific child state is bein ...

Javascript redirection not functioning correctly

Currently, I am working with PHP Codeigniter. The current URL of my page is => http://localhost.hbs.com/hbs/merchant/login I want to redirect my page to => http://localhost.hbs.com/hbs/category when a specific event occurs. I have attempted to achie ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

Failure of ng-click to transmit latest value

Here is the code snippet I am working with: <div class="input-field col s3" ng-repeat="data in content.data"> <input class="updatable mcq" ng-disabled="!viewMode" type="checkbox" id="mcq{{data.surveyPropertyId}}" ...

Retrieve the selected options from the checkbox and transfer them to the input text field

In the following example, I am attempting to extract all values of the inputs once they are checked and display them in a text input that will be sent via email. However, I am facing an issue where only the last option is being printed in that input instea ...