AngularJS: Utilizing forEach with http get requests to ensure all data is loaded before proceeding

Imagine you have an article with comments.

The data structure looks something like this:

  {ArticleId...., someFields...., Comments: [{AuthorId:1, Text:''}, {AuthorId:2, Text:''}, {AuthorId:3, Text:''}]}

When trying to retrieve user information (such as avatar and name) through the endpoint: /user/{id}

(this is only triggered when a user clicks on the comments...)

$scope.getUserData = function(el) {
  $http.get(settings.apiBaseUri + '/app/users/' + el.AuthorId, {
    headers: {
      'Content-Type': 'application/json',
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'If-Modified-Since': ''
    }
  })
  .success(function(response) {
    /*store some data*/
  });
});

$scope.getArticleData = function(){
    angular.forEach($scope.article.Comments, function(el) {
        $scope.getUserData(el.AuthorId);
    });
    /*How can I ensure that my forEach loop has completed all tasks (including loading of all http data) before running a new method?*/
};

How can I ensure that my forEach loop has completed all tasks (including loading of all http data) before running a new method?

Answer №1

To tackle this issue, you could consider utilizing a promise array that holds promises generated by $http. One potential approach is as follows:

$scope.getUserData = function(el) {
  var promise = $http.get(settings.apiBaseUri + '/app/users/' + el.AuthorId, {
    headers: {
      'Content-Type': 'application/json',
      'Pragma': 'no-cache',
      'Cache-Control': 'no-cache',
      'If-Modified-Since': ''
    }
  })
  .success(function(response) {
    /*store some data*/
  });
  return promise;
});

$scope.getArticleData = function(){
    var promises = [];
    angular.forEach($scope.article.Comments, function(el, promises) {
        promises.push($scope.getUserData(el.AuthorId));
    });
    $q.all(promises).then(/*Custom logic here*/);
};

Alternatively, for a cleaner setup as suggested by @sdgluck:

$scope.getArticleData = function(){
        var promises = $scope.article.Comments.map(function() {
          return $scope.getUserData(el.AuthorId);
        });
        $q.all(promises).then(/*Custom logic here*/);
    };

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

Generating an array of strings that is populated within the Promise handler

If I come across code like this in my Ionic/Angular/TypeScript project... let arr: Array<string> = []; this.databaseProvider.getAllSpecies().then(allSpecies => { for(let species of allSpecies) { if(species.name.toLowerCase().indexOf(keyword ...

Maintaining microsecond accuracy when transferring datetime values between Django and JavaScript

It appears that django, or the sqlite database, is saving datetimes with microsecond precision. However, when it comes to transferring a time to javascript, the Date object only works with milliseconds: var stringFromDjango = "2015-08-01 01:24:58.520124+1 ...

Can you explain the significance of module.exports? And what is the reasoning behind naming it "module"?

I have another question in regards to learning express as a beginner. Can anyone recommend any helpful websites for someone new to this technology? I find that the official documentations can be quite unclear and overwhelming at times for beginners. Any ...

When displaying content within an iframe, toggle the visibility of div elements

I'm attempting to toggle the visibility of certain page elements based on whether the page is loaded in an iframe. <script>this.top.location !== this.location && (this.top.location = this.location);</script> The above code succes ...

Which entity is responsible for supplying the next() function within Express middleware?

I'm trying to understand the workings of next() in Node.js and Express middleware. While there have been previous inquiries regarding middleware operations, such as this one, I am seeking a fresh perspective. The primary query troubling me is: who s ...

Tips for changing the state of a parent DOM element from a child component several levels deep in a React application

I am currently incorporating both react-router-dom and Material-UI into my application. Below is a basic example I have created using the following files: routes.tsx import { Outlet, createBrowserRouter } from "react-router-dom" const App = () ...

Creating a subclass or extending a Promise in Typescript does not require referencing a constructor value that is compatible with Promises

I am currently working on a way to terminate my async method call in Typescript. In order to achieve this, I decided to create a new type of Promise that extends from the standard Promise: class CustomPromise<T> extends Promise<T>{ priva ...

Guide on waiting for promise from UI Router Resolve within an Angular 1.5 Component

Help needed with Angular 1.5 Component and Resolve for data retrieval Seeking guidance on utilizing Resolve to fetch data. Plunker: https://plnkr.co/edit/2wv4YWn8YQvow6FDcGV0 <!DOCTYPE html> <html ng-app="app"> <head> <meta c ...

Determine all the names of imported files in a source file using regular expressions in JavaScript

Hello, I'm new to working with regex and JavaScript. I'm attempting to use regex to create an array of all imported files in a source file. In the source file, there is an '@' sign before an import statement. For example, if the file lo ...

Encountered a TypeError during back button press on Angular UI-Router: "a.indexOf is not a

Currently, I'm developing a web application using Angular 1.6.1 with Angular Material and ui-router modules integrated. Transitioning from one state to another works seamlessly, however, an issue arises when the browser's back button is clicked ...

Is there a way for me to customize the default icon displayed in the "clear" option of the textAngular directive toolbar?

I am curious about the textAngular directive (https://github.com/fraywing/textAngular) and its various presets such as adding links, blockquotes, etc. However, I am specifically interested in how to customize the default icon for clearing formatting on t ...

Creating a dynamic `v-model` for computed properties that is dependent on the route parameter

I am creating a versatile component that can update different vuex properties based on the route parameter passed. Below is a simplified version of the code: <template> <div> <input v-model="this[$route.params.name]"/> </div&g ...

Tips on how to trigger the function upon receiving the response value by concurrently running two asynchronous functions

export default { data: () =>({ data1: [], data2: [], lastData: [] }), mounted() { asynchronous1(val, (data)=>{ return this.data1 = data }) asynchronous2(val, (data)=>{ return this.data2 = data }) f ...

.then function not functioning properly in Axios DELETE request in a React project

I am currently facing an issue with calling a function to update the array of notes after deleting a note from the database. The function causing the error is called deleteNote, and the function I intend to call within the .then promise is getNotes. Here i ...

Navigating to the parent node in a treeview within the wijmo flex grid: a step-by-step guide

Utilizing the wijmo flex grid, I've successfully created a tree view for my data. I can determine if a specific node has children and its level, but I'm struggling to navigate to the parent node from a given one. Additionally, I am able to retrie ...

Tips for incorporating a multiple tag search feature within my image collection using JavaScript?

I am facing a challenge with my image gallery search feature. Currently, users can search for images by typing in the title or tag of an image. However, I need to enhance this functionality to allow for multiple tags to be searched at once. For example, if ...

The useEffect function continues to re-render

When developing a React app, I encountered an issue where my component was stuck in a re-rendering loop due to an HTTP request handling process using useEffect and custom hooks. In order to fix this problem, I added a layer of services to properly parse th ...

An issue has been encountered in NodeJS with a route that begins with a percent sign causing an error

I have a NodeJS server set up with the following backend configuration: app.use(express.static(__dirname)) app.get('/', function(req, res){ res.send('main page here') }); app.get('/*', function(req, res){ res.send(&apos ...

How can user data be logged in ASP.Net Core when a check box is selected?

Struggling to discover a way to secretly log user information such as their username when a checkbox is selected. The goal is to capture this data without the user's knowledge. Here is the code: This checkbox is a custom switch from MDB <div> ...

The essence of the argument becomes muddled when implementing bind apply with arrays as arguments

I referenced this particular solution to create a new instance of a class by passing array arguments using the code snippet below: new ( Cls.bind.apply( Cls, arguments ) )(); However, I encountered an issue where one of my arguments is an array and the v ...