Ensure that you wait for all asynchronous $http requests to finish in AngularJS before continuing

I am facing a challenge with a page that generates a varying number of $http requests based on the length of a certain variable. I aim to update the scope with the data only after all requests have been completed. Without relying on jQuery for this project, I seek a solution that does not involve jQuery. Currently, the data is being sent to the scope as each request finishes, which is not the desired behavior.

Below is a snippet of the code I have implemented so far:

for (var a = 0; a < subs.length; a++) {
  $http.get(url).success(function (data) {
    for (var i = 0; i < data.children.length; i++) {
      rData[data.children.name] = data.children.age;
    }
  });
}

One part that concerns me is the argument required for $q.all() method, which is not clearly explained in the Angular documentation, leaving me unsure of how to proceed.

$q.all().then(function () {
  $scope.rData = rData;
});

I appreciate any assistance in resolving this issue. Thank you.

Answer №1

$http always returns a promise that can be utilized with the $q.all function.

var one = $http.get(...);
var two = $http.get(...);

$q.all([one, two]).then(...);

More information on this behavior can be found in the official documentation:

all(promises)

promises - An array or hash of promises.

To implement this in your case, you will need to create an array and push all the calls into it in a loop. This will allow you to use $q.all(…) on your array similarly to the example provided above:

var arr = [];

for (var a = 0; a < subs.length; ++a) {
    arr.push($http.get(url));
}

$q.all(arr).then(function (ret) {
    // ret[0] contains the response of the first call
    // ret[1] contains the second response
    // and so on.
});

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

Troubleshooting: ng-disabled feature is not properly functioning with Bootstrap buttons

I am currently using a combination of bootstrap.js and angular js in my project. The code snippet I have is as follows: //snippet from the controller $scope.isWaiting = true; $scope.promise = $http.get("voluumHandler.php?q=campaigns&filter=traffic-sou ...

Firefox displays an error when using jQuery.load(), but Chrome functions properly without any issues

I have created a function that opens a page in a dialog box instead of the main window. The code has been cleaned up and here is the revised version: var baseUrl = window.location.origin + '/static/docs/'; function handleLinkClick(event) { ev ...

Submit a post request using a Trigger.io-powered mobile application

Essentially, I need my mobile app (created with Trigger) to send a Post request to a remote server. The app generates GPS coordinates and timestamps, then sends this data to a server (built using Ruby on Rails) for storage. I am utilizing the Zepto library ...

Leveraging properties in computed Vue.js

I have a computed property that looks like this: display() { return this.labs.map(function(x, i) { return [x, this.plotDt[i]]; }); } This property receives data as props: props: ["plotDt", "labs"], Both plotDt and labs are ar ...

Eliminate redundant data by utilizing oData to streamline information

I'm trying to clean up my data and eliminate duplicates using oDATA. Currently, I am using !summary=Name in my query, however it's not creating groups and providing the results as expected. Below is my query: http://localhost:12585/OData.svc/Med ...

I'm having trouble retrieving my variable within the socketcluster's socket.on function

How can I store the value of msg in the variable sample when sample is not accessible inside the callback function? import { Injectable } from '@angular/core'; import * as socketCluster from 'socketcluster-client'; @Injectable({ pro ...

What is the process for navigating through $http response code sections in a web browser?

I'm currently debugging some code to identify a strange behavior in my application. Whenever I reach an $http.post function call, I am only able to step through the initial function call, the .success function call, and the .error function call. Unf ...

Instructions on creating a non-editable text area where only copying and pasting is allowed

I am looking to simply copy and paste content into a textarea without needing to make any edits within the field. <form action="save.php" method="post"> <h3>Text:</h3> <textarea name="text" rows="4" cols="50"></textarea ...

Matching utility types and themes in Tailwind CSS

I encountered an issue while trying to implement the Tailwind plugin in my project. It seems that a TypeScript error has occurred. I'm curious about the data types of matchUtilities and themes. Can someone provide some insight? const plugin = require( ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

The deletion of $window.sessionStorage.token does not appear to be functioning properly during the logout process

I developed an application using angularjs and nodejs with jwt token based authentication. The issue arises when a user logs out of the application as they are redirected to the login page. However, upon logging back in, the URL remains the same. If the u ...

In certain situations, Chrome and Safari fail to trigger the unload function

Struggling with a persistent issue lately and really in need of some assistance. My goal is to perform a server-side callback to clear certain objects when the user navigates away from our page, without needing to click logout. Due to business requirements ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

Error in Vue Google Maps: Marker not defined

I'm currently working on integrating a single location map using Google Maps in Vue 2 with Vue-google-maps-2. Despite using code that has successfully worked for other parts of the application where multiple markers are plotted from an array, I am enc ...

Transforming data from an HTML form into a PDF document - Tips for generating multiple outputs

As a newcomer to coding, I am facing a challenge in passing input data from a form to a PHP response page and then displaying it in the browser. I have created a functionality where the user can click on a button to save the HTML element to PDF. However, I ...

When adding files through drag and drop, the FormData is including a blank file field in the sent

I am currently working on a photo upload page that has drag and drop functionality enabled. Below is the form code: <form id="Upload" method="post" action="sessionapi/UserPicture/Upload" enctype="multipart/form-data"> <input class="box__file ...

Retrieving the checked value of a checkbox in Angular instead of a boolean value

Currently I am working on a project using ServiceNow and AngularJS. I am having trouble obtaining the value of a checkbox. Here is the code snippet: $scope.userFavourite = function(favourite){ alert(favourite); } <labe for="tea"& ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

What is the best way to mention @here with an attachment?

I'm attempting to use the canvas say command to display an image with an @here mention included, but unfortunately it only shows the image without making the mention. Below is what I have attempted: message.channel.send(`@here\n`+attachment); ...

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...