Function containing the $http.get method

I am facing an issue with my function containing multiple $http get requests. Despite needing to call another function after each request is completed, it always executes the function before the request finishes processing. What could be causing this and are there any solutions to resolve it?

$scope.json=function(){
        $scope.loading = true;
        $http.get(DataElementUrl).then(function (response) {
            if (!response.data == "")
            dataElementJson = response.data;

        });
        $http.get(categoryComboUrl).then(function (response) {
                if (!response.data == "")
                    categoryComboJson = response.data;                   
        });
        $http.get(categoryUrl).then(function (response) {
                    if (!response.data == "")
                       categoryJson = response.data;                        
        });
        check++;
        $scope.getJson();
};

Answer №1

To utilize the 'all' function of $q, follow this code snippet:

    var x = $http.get(DataElementUrl).then(function (response) {
        if (!response.data == "")
            dataElementJson = response.data;
    });
    
    var y = $http.get(categoryComboUrl).then(function (response) {
        if (!response.data == "")
            categoryComboJson = response.data;                   
    });
    
    var z = $http.get(categoryUrl).then(function (response) {
        if (!response.data == "")
           categoryJson = response.data;                        
    });

    $q.all([x, y, z]).then(function(result) {
      performAction++;
      $scope.fetchData();
    });

Answer №2

The reason why this is happening is because of the asynchronous nature of network calls in JavaScript. To resolve this issue, you can explore the q service provided by Angular. This service functions as a promise library.

If you need to execute a method only after all three promises have been completed, you should utilize:

.all([promise1, promise2], fulfilled, rejected)

This will trigger the fulfilled callback once all promises in the array have been fulfilled.

Answer №3

This is how I would implement $q.all() in my code:

$scope.fetchData = function(){
    $scope.loading = true;

    var promises = [$http.get(DataElementUrl),
                    $http.get(categoryComboUrl),
                    $http.get(categoryUrl)]

    $q.all(promises).then(function(results){
          dataElementJson = results[0].data,
          categoryComboJson = results[1].data,
          categoryJson = results[2].data
    });
};

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

There is a syntax error that occurs when attempting to begin a key with a hyphen (-)

Upon initializing the following object, an error is thrown. var postData ={ file_path : "https://s3-us-west-2.amazonaws.com/ps/eams/6-48K.mxf", template_type : "1", template_name : "Basic Tests", job_type : "0", user_note : "my job", access-ke ...

The child_process module has yet to be loaded

Exploring NodeJS to execute a PowerShell script from JavaScript. Found this code snippet online: var spawn = require("child_process").spawn, child; child = spawn("powershell.exe",["c:\\test\\mypstest.ps1 -arg1 1"]); child.stdout.on(" ...

Dynamic way to fetch computed properties in VueJS

I am trying to find a way to calculate the sum of computed properties that begin with the string calculateSum. The challenge is that I cannot access their names using this.computed. Here is my approach: getSubTotal(){ var computed_names = []; var ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...

What is the best way to upload an image through PHP using $_POST after using JavaScript to resize it?

I am currently working on developing a webpage that allows users to upload images from their iPhone, Android, and desktop devices. The goal is to save these pictures as thumbnails in the ./userupload directory and store the link to them in a MySQL database ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Filtering the Scope in AngularJS onClick Event

Looking to add an alert button to display the filtered object from my Angular filter data. I have successfully retrieved the desired object in my HTML template using: {{(portals|myFilter:or| filter:search )}} Here is my button: <a ng-href='#here& ...

How to send information to a modal component in ReactJS?

I'm feeling a bit lost here, maybe I'm missing something. What I am trying to achieve is a loop that populates an array with progress bar elements and then displays them with the relevant information. When a user clicks on a progress bar, the d ...

Setting the data type for a React Stateless Functional Component (SFC) in TypeScript

By assigning a type of React.FC<PropsType> to a variable, it becomes recognized as a React Stateless Functional Component. Here's an example: //Interface declaration interface ButtonProps { color: string, text: string, disabled?: boolean ...

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

Different ways to loop through varying grid dimensions

I'm struggling to find a solution to the following problem: I have 5 grids in a row with sizes md={2}, md={3}, md={2}, md={2}, md={3} Now I need to loop through them, but since the grid sizes are different, how can I manage them? <Grid item xs={ ...

Tips on concealing all classes except one through touch swiping

If you have a website with a single large article divided into multiple sections categorized as Title, Book1, Book2, & Book3, and you want to implement a swipe functionality where only one section is displayed at a time, you may encounter some issues. ...

How can I create a pop-out message box in HTML similar to the style used in Gmail or OkC

As someone who isn't very experienced in client development, I hope you'll forgive me for asking what might be a simple question that can easily be solved with Firebug. I'm interested in learning how to create a feature like the OKCupid or G ...

How can I acquire a duplicate of a Webgl texture?

I have a webgl texture and I have stored it in a JavaScript variable var texture1 = CreateTexture() function CreateTexture(){ var texture = gl.createTexture() // more WebGL texture creation code here return texture } I am looking to create a copy o ...

The unexpected disappearance of data in a d3 v4 map leaves users puzzled

My current task involves reading data from a csv file and creating a map where the key is the state abbreviation and the value is the frequency of that state in the data. The code I have successfully creates the map, reads in the data, and when I use cons ...

Flask - Refreshing Forms Dynamically

In an effort to enhance the responsiveness of my app, I am looking for a way to prevent the page from reloading every time a POST request is sent. My current setup includes a dynamically generated form with input fields designed like this: <div class=&q ...

The attempt to initialize module ui.grid.validate was unsuccessful

I've been working on implementing validation in ui.grid. I have injected 'ui.grid.edit' and 'ui.grid.validate' into my module, but I keep encountering an error. Error: [$injector:modulerr] Failed to instantiate module ui.grid.vali ...

How can I use the same popup button to open a different link in a new tab?

I have a situation where I am using a button to trigger an ajax html popup. What I want is for the same button, when clicked, to open another page in a new tab. Any assistance would be greatly appreciated. Below is the HTML code I am currently using: < ...

The specified module could not be located:

Just starting out with Vue.js, I stumbled upon a Medium article about the MEVN architecture. Here's a snippet of code from a component that I've been working on for the past two days: <template> <div class="post"> <h ...

Converting dynamic text enclosed in asterisks (*) into a hyperlink on a webpage with the use of JavaScript

I'm facing a unique situation where I need to transform specific text on an HTML page into anchor tags using JavaScript/jQuery. The text format is as follows: *www.google.co.uk/Google* *www.stackoverflow.com/StackOverflow* The desired outcome should ...