AngularJS gathers information through a series of $http requests loop

Currently, I am facing an issue with a loop in my client API. The loop is supposed to add data returned from an API call as an object to an object array in each iteration and then display the content of the object array at the end of the loop.

However, due to the asynchronous nature of JS code execution, when trying to display the content of the object array, it always returns undefined. I am seeking assistance in finding a solution to this problem. Your help would be greatly appreciated. Thank you.

  var invoiceObj = {};
  var invoiceObjArray = [];
  for (var i=0; i< 5; i++)
  {
      //getAllInvoices returns a promise from $http.GET calls...
      ClientInvoiceService.getAllInvoices(i).then(function(invoice){

             invoiceObj = { invoiceNum: invoice.Result[0].id,
                            clientName: invoice.Result[0].clientName};

             invoiceObjArray.push(invoiceObj);   

         }, function(status){
            console.log(status);
         });

  }

  console.log(invoiceObjArray[0]); //return undefined
  console.log(invoiceObjArray[1]); //return undefined

Answer №1

To efficiently manage multiple promises in AngularJS, you can store them all and then pass them to $q.all (scroll all the way down). This method wraps all promises into one big promise that will only be resolved if all individual promises are resolved.

Make sure to update your code as follows:

var invoiceObj = {};
var invoiceObjArray = [];
var promises = [];
for (var i=0; i< 5; i++)
{
      //getAllInvoices returns a promise...
      promises.push(ClientInvoiceService.getAllInvoices(i).then(function(invoice){

             invoiceObj = { invoiceNum: invoice.Result[0].id,
                            clientName: invoice.Result[0].clientName};

             invoiceObjArray.push(invoiceObj);   

         }, function(status){
            console.log(status);
         }));

}
$q.all(promises).then(function(){
    console.log(invoiceObjArray[0]);
});

For a helpful tutorial on using $q.all, check out this Egghead video.

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

Arranging objects in an array based on their specific property

My DataBase collection looks like this: var items = [{ 'Name':'Michael', 'TypeId':1 } { 'Name':'Max', 'TypeId':1 } { 'Name':'Andre', 'TypeId':1 } ...

Is there a method to keep the leftmost column in a Google visualization table anchored in place when scrolling horizontally?

I want to replicate the typical google visualization table header row functionality, but I would like it to be focused on the first column instead. It doesn't appear to be a default feature, so I'm curious if it could be achieved using custom CSS ...

Attempting to retrieve XML/JSON

I am struggling with extracting the first 15 words from a file using the API. I have attempted to do it with both XML and JSON, but keep encountering this error: XMLHttpRequest cannot load No 'Access-Control-Allow-Origin' header is present on th ...

webdriverio fails to render the page on the browser

Running Ubuntu 14.04 and encountering an issue with the following code: var webdriverio = require('webdriverio'); var options = { desiredCapabilities: { browserName: 'firefox' } } webdriverio .remote(options) ...

Dealing with unhandled exceptions while passing promises into pg-promise batch transactions

Currently, I am diving into the realm of learning express and pg promise. However, during this journey, I have encountered a puzzling issue that I suspect stems from my somewhat shaky understanding of promises. Essentially, I have crafted some functions f ...

To apply a background color to a specific <td>, simply enter the position number into the 3rd textbox using JavaScript

I have successfully implemented three textboxes in my project. The first textbox is for entering a number as the row count The second textbox is for entering a number as the column count The third textbox is used to specify a position in the table that ...

jest - SyntaxError: Unexpected token 'export'

I am currently utilizing vue.js and attempting to incorporate async/await in jest (with vue utils test). it('async/await test', async () => { await wrapper.setData({ foo: 'bar', }); // ... }); Although I can us ...

Using AJAX to send both data input values and file attachments simultaneously to a PHP server

I am currently having an issue with sending form values to my PHP page using AJAX. My form includes text inputs and a file input for image uploads. Below are the AJAX codes I have been working on: function sendval() { var form = $('#user_update_for ...

What is the best way to retrieve the value of an nth column in a table using

Is there a way to retrieve the value of a specific column in a table? For example, I want to get the value of the 2nd column. I have no trouble getting the first one using this method - it works perfectly fine. However, when I try to retrieve the value of ...

Issue with Angular ng-repeat not updating after array push

Struggling to grasp Angular concepts such as scopes has been a challenge for me. Recently, I encountered an issue where ng-repeat was not updating after adding a new 'wire' to my array. I suspected it could be due to the array being out of scope ...

What can be done to address columns overlapping when sidebar is activated?

Excellent https://i.sstatic.net/gwOI8.png Terrible https://i.sstatic.net/4f637.png The first image labeled as 'Excellent' shows that the card divs do not overlap, but in the second image when the sidebar is active they do. I attempted to cha ...

What could be causing the 401 status code in my sign_in.json request? (Guide on AngularJS and Rails from Thinkster)

Currently, I have been diligently following the AngularJS Tutorial for Rails on Thinkster and am now approaching the conclusion of User Authentication with Devise. The application appears to be functioning properly on my local server, but upon inspecting t ...

Regular expression that prohibits the acceptance of numbers with leading zeros

Below is the directive I am using to ensure that the input consists purely of numbers from 0-9. import { Directive, HostListener, ElementRef } from "@angular/core"; @Directive({ selector: "[numbersOnly]", }) export class OnlynumberDi ...

Edit images prior to uploading to the server by adjusting the size or dimensions as raw binary data (format should be either png or jpeg

In my quest to crop images in the browser and upload them directly to a server as raw image binary data (either in "image/jpeg" or "image/png" format), I have tried various client-side methods for cropping and uploading. These methods typically utilize the ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

AngularJS ng-repeat inside a directive executed twice

Check out this Plunker for the code function DirectiveController($scope, $element) { $scope.Array = ["a", "b"]; $scope.me = function() { console.log("i ran"); }; }; //Directive HTML <div class="cool picker" ng-repeat="item in A ...

Triggering the click event three times on a dynamically generated element

I am currently facing a simple issue. I am attempting to implement a click event on dynamically generated elements such as this: $(document).ready(function(){ $('ul').on('click', 'li.clickable', function() { conso ...

"Bringing angular2-cookie into an angular4 project: A step-by-step guide

I am currently facing an issue while trying to integrate angular2-cookie into my angular4 project. The project I am working on is developed with Angular and, in particular, here is the content of my package.json: { "name": "ng-admin", "version": "0.0 ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

Getting the result from a JavaScript request, whether it's synchronous or asynchronous

This code snippet involves a function that starts with a synchronous comparison test == 0. If the comparison is true, it returns one piece of content; however, if it's not, an asynchronous request is made. The goal here is for the latter part to retur ...