Struggling with ensuring that Angular-JS pauses and waits for an asynchronous call to complete before moving on

Understanding the use of promises in Angular for handling async operations is crucial, but I'm struggling to implement it effectively in this scenario.

function fetchLineGraphData(promises){
    var dataPoints = [];
    for (var i = 0; i < promises.length; i++) {
        $http.get('/file/tsDataPoints/'+promises[i].unit+"?startDate="+promises[i].startTs+"&endDate="+promises[i].endTs+"&startState="+promises[i].startState+"&endState="+promises[i].endState).success(function(data){
            dataPoints.push(data);
            console.log(data);
        });
    }
    console.log(dataPoints);
    return dataPoints;
}

The challenge lies in dealing with an array of data to construct multiple queries instead of just one. How should I approach this? Any concrete examples or guidance would be greatly appreciated. Thank you.

Answer №1

When using $http in AngularJS, it returns a promise. By combining $q.all with an array of promises, you can ensure that all promises are resolved before proceeding. Here's how you can achieve this:

promises = promises.map(function(promise){
    return $http.get('/fetch/data/'+promise.id+"?start="+promise.startDate+"&end="+promise.endDate);
});

$q.all(promises).then(function(resultsArray){
    console.log(resultsArray); // array containing results from all the $http requests
});

Note:
If you need to actually return the data from a function, you can do so like this:

function fetchData(promises){
    promises = promises.map(function(promise){
        return $http.get('/fetch/data/'+promise.id+"?start="+promise.startDate+"&end="+promise.endDate);
    });        
    return $q.all(promises);
}

You can then call the function like this:

fetchData(dataPromises).then(function(resultsArray){ 
    // handle the results accordingly
});

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

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...

Having trouble with the automatic closing feature of Bootstrap drop down in React?

While using the drop button feature of Bootstrap, I have encountered a situation where it works fine when clicked on, but disabling it by clicking outside using autoClose='outside' does not seem to work as expected. When I click on my hamburge ...

Guide to adding items to an array in json-server using a JavaScript-created database

I built a JSON-server app that dynamically generates the database using JavaScript when it starts running. The data I create is organized within a 'users' object, as illustrated below: { "users": [ { "id": "user_id_0", ...

Update the HTML page when switching between tabs

Currently, I am experiencing an issue with tab navigation in HTML. Within my code, I have two tabs named #tab1 and #tab2, each containing a form. The problem arises when I input data into #tab1, switch to #tab2, and then return to #tab1 - the information I ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

The functionality of CKEDITOR.tools.getindex has not been found

I'm currently in the process of updating my CKEDITOR version from 4.4.1 to 4.5.1. In order to do this, I am uploading my build-config.js file to ensure that I have all the same plugins as before with the latest CKEDITOR version. The issue arises when ...

Exploring ways to assign a value to an HTML element utilizing Jquery in combination with ASP.NET MVC 4 complex model information

Within an ASP.NET MVC 4 view, I am utilizing data from a Model to populate various HTML elements. The model is used in the view to showcase values like: <div>@Model.Category.Name</div> etc... However, there is a specific div tag <div id="D ...

Despite the correct value being displayed in the console.log, the Textfield is not responding to the Reducer

I am currently working on a project to create a tool that can iterate through the pupils of a school class. In order to achieve this, I have implemented a text field in a react component that displays a value: <input className="form-control" onChange={ ...

``There seems to be a malfunction with the modal feature in the asp.net

Within my strongly typed view, I have a loop that iterates over a list of objects fetched from a database. Each object is displayed within a jumbotron element, accompanied by a button labeled "Had role before". When this button is clicked, a modal opens wh ...

Emulate the CSS hover effect with jQuery 코드 희미한

Is there a method in jquery or any other technology that can detect event X and trigger a different event elsewhere? Currently, I am working with an image that has an image map. When a user hovers over a specific area on the map, I would like another part ...

The combination of loading and scrolling JavaScript code is not functioning properly on the website

I created an HTML webpage that includes some JavaScript code to enhance the user experience. However, I encountered an issue when trying to incorporate a load JavaScript function alongside the scroll JavaScript function on my page. The load script is posi ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...

Unable to designate decimal value as the default in DropdownListFor in ASP.NET Core when utilizing JavaScript

Everything appears to be functioning properly, except when dealing with decimal values in the following code snippet: $('select#listspec_0__qty option[value = 105.3]').attr("selected", true); ...

Jasmine spying on a standalone function that is not a method of an object

What is the best way to spy on a function that is not a method of an object? In my specific case, the function callMe is not defined on the window object - it is a dependency loaded through angular. if (X) { callMe('hello'); } ...

Is it necessary to encode the content before transmitting HTML in JSON from the server to the client?

When it comes to sending HTML content from the server to the client for displaying user comments in a rich JS app that communicates through a JSON API, there are some considerations to keep in mind. One important question is how to handle the content with ...

How can I generate a true or false response for an AJAX form submission depending on the data received from a PHP file?

I only want the form to be submitted if the data returned from the PHP file is "available". If not, the submission should not occur. function PostData() { var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (w ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...

Utilizing the .map() function to retrieve an object from an array without a key

Exploring Dialogflow, I aim to retrieve the speech value for the object in the messages array that lacks a platform key: "messages": [ { "type": 0, "platform": "skype", "speech": "FOO" }, { "type": 0, "platform": ...

Looking for guidance on restructuring a JSON object?

As I prepare to restructure a vast amount of JSON Object data for an upcoming summer class assignment, I am faced with the challenge of converting it into a more suitable format. Unfortunately, the current state of the data does not align with my requireme ...