Handling callback functions in JavaScript when using the $http.get method

My task involves retrieving multiple http.get requests from a server with different json sets.

After processing each "physical" data set, I need to perform a calculation that requires the value from the corresponding "virtual" call. This calculation is handled by a function called "Calculate" (refer to code snippet below)

Most of the time, this process works smoothly and accurate values are generated. However, there are instances where the $http.get requests do not finish in time, resulting in the values remaining at 0.

How can I ensure that both http.get requests for the physical and virtual calls complete successfully for every "cluster"?

function($scope, $http) {
// Code logic for handling multiple http.get requests...
    
function calculate(string, type, virtual, physical) {

    console.log(type + " capacity " + string + ": " + (virtual / physical).toFixed(2) * 100 + "%");

}
}]);

Answer №1

If it is possible to execute them simultaneously, then initiate all of them at the same time and utilize a $q.all method that will be resolved once all promises are fulfilled:

var promiseList = {};
promiseList.virtual1 = $http.get('http:///search?idc=LH5&type=Virtual&cluster=1');
promiseList.virtual2 = $http.get('http:///search?idc=LH5&type=Virtual&cluster=2');
promiseList.physical1 = $http.get('http:///search?idc=LH5&type=Physical&cluster=1');

$q.all(promiseList).then(function (outcomes) {
    // outcomes.virtual1 will contain the results from virtual / cluster 1 promise
    // outcomes.virtual2 will contain the results from virtual / cluster 2
});

Answer №2

When you want to make your HTTP requests run concurrently, you can include $q and utilize $q.all() in the following manner:

var httpRequests = [
    $http.get(/* .... */),
    $http.get(/* .... */),
    // add more as needed
];

$q.all(httpRequests).then(function(response) {
    console.log('All requests completed, response:', response);
});

Answer №3

Your method of handling calls seems to be incorrect when tailing the calls. The calls appear to be capable of being executed simultaneously, updating independent states tcores[1..5] and tmemory[1..5]. To achieve this, you can make the calls individually and then consolidate them into a large promise that resolves only when all the calls have successfully resolved using $q.all.

var core1 = $http.get('http:///search?idc=LH5&type=Virtual&cluster=1').success(function(data) {
    $scope.servers = data; // retrieve data from JSON
    angular.forEach($scope.servers, function(item) {
        if (parseInt(item.cores) != "NaN" && item.cores != "") {
            if (angular.isNumber(parseInt(item.cores))) {
                tcores1 = parseInt(tcores1) + parseInt(item.cores);
                tmemory1 = parseInt(tmemory1) + parseInt(item.memory);
            }
        }

    })
    console.log("Hall 5. Cluster 1 Total Cores: " + tcores1);
    console.log("Hall 5. Cluster 1 Total Memory: " + tmemory1);
});


var core2 = $http.get('http:///search?idc=LH5&type=Virtual&cluster=2').success(function(data) {

    $scope.servers = data; // retrieve data from JSON
    angular.forEach($scope.servers, function(item) {
        if (parseInt(item.cores) != "NaN" && item.cores != "") {
            if (angular.isNumber(parseInt(item.cores))) {
                tcores2 = parseInt(tcores2) + parseInt(item.cores);
                tmemory2 = parseInt(tmemory2) + parseInt(item.memory);
            }
        }

    })
    console.log("Hall 5. Cluster 2 Total Cores: " + tcores2);
    console.log("Hall 5. Cluster 2 Total Memory: " + tmemory2);
});

// ...

var allRequestsComplete = false;
$q.all([core1, core2, core3, core4, core5]).then(function () {
     allRequestsComplete = true;
});

function calculate() {
    if (!allRequestsComplete) {
          console.log(type + " capacity " + string + ": " + (virtual / physical).toFixed(2) * 100 + "%");
    } else {
          console.log('Calculation in progress.');
    }
}

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

When you try to import from another file, the method is not defined

When I attempt to import a method from another file, I am encountering an issue where it returns undefined. The structure involves 3 files with one calling the next in sequence. File1: const { methodFromFile2 } = require('./file2'); methodFromFi ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

Stop the repetition of the HTML Script element running more than once

Currently, I am using Ionic 2 for the development of my app. Inside the index.html file, there are various scripts that execute when the application starts. My goal is to rerun app.bundle.js midway through a user's interaction with the app. Here is ...

What is the appropriate method for transferring a JSON string from JavaScript to PHP and vice versa?

As I strive to transmit a small amount of data from JavaScript by means of XMLHttpRequest and a Json string to a PHP script for processing, only to receive a corresponding Json string in response, I have encountered numerous obstacles and various technique ...

The image remains unchanged in the JavaScript function

My attempt to swap images using jQuery has hit a snag. Upon running the page, it appears that the chase() method finishes executing before the animation has completed. The goal was to create an illusion of chasing between two images by repeatedly replaci ...

Difficulty paginating jqgrid when using an array as the data source

Encountering an issue with pagination in jqgrid while working with array data containing 18 records. Even after specifying pagination:true, pager:jQuery('#pager1'), the records are not displaying in pages. Can anyone assist me in implementing pag ...

Expand the grid with extra rows once it has been generated, especially when dealing with a large volume of database records, utilizing JQGrid or JSGrid

Having a large dataset (json) that takes too long to display in the grid for users, I'm looking for a solution. My idea is to initially run a filtered query (e.g. records from the current year) to quickly build the grid. Once the grid is presented to ...

Retrieving ng-repeat $index with filtering in AngularJS controller

I am facing a challenge with my ng-repeat list and filter in AngularJS. I am unable to retrieve the visible $index value from inside my controller. Although I can display the index easily and see it change dynamically when the list is filtered, I am strug ...

React is throwing a parsing error due to the incorrect use of braces. Remember, JSX elements must be wrapped in an enclosing tag. If you were trying to include multiple elements without a parent tag, you can use a JSX fragment

Having recently started working with React, I came across this code snippet return ( <div> dropdown ? (<li className='goal-list-item' onClick={() => setDropdown(!dropdown)}>{goal.name}</li>) : ...

Learn how to efficiently handle responses from two API calls in AngularJS using the powerful $q.all method along with a service

I am attempting to make calls to two APIs and store the responses in scope variables. However, I am encountering an issue where I cannot access the data in the scope variable. I am using $q.all and a service to make the API calls. Error: angular.js:88 ...

Is it better to parse HTML in PHP or JavaScript for an iPhone web application?

I am in the process of creating a web application for iPhone/iPod touch. I need to incorporate an external HTML file and extract specific data from it. One approach is to handle this on the server side by creating a separate page that echoes the desired d ...

Retrieve tag, custom taxonomy, and attachment information using the get_pages function

Currently, I have implemented code that retrieves all pages submitted by the currently logged-in author using the get_pages function. The retrieved result is then passed to Javascript via Ajax. Everything functions as expected, and the correct pages are be ...

Display the hidden div element when clicked

In my code, I have two div elements as follows: <div class='staticMap'></div> <div class='geolocation-common-map'></div> Initially, the 'geolocation-common-map' div is removed using jQuery when the pa ...

Error: Cannot set value on a property that is designated as a getter-only in Vue.js using

My current task involves taking an image as input, converting it into a base64 string, preparing a payload containing the base64 string, and sending a post request to the backend. I then need to retrieve the response data and preview the base64 image from ...

Tips for Retrieving Information from Firebase in an Angular Application

I am facing an issue with my code where the ngFor directive is not working as expected when I use read_CheckOuts to return data from the database. Below are snippets of my code: crud.service.ts import { AngularFireDatabase} from '@angular/fire/datab ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

Update the picture dynamically when hovering

Is there a way to change an image randomly when hovering over it? The hover effect is working fine, but the image does not revert back when the mouse moves out. Any suggestions on how to fix this? var arr = ["020", "053", "306", "035", "930"]; function ...

Preventing click propagation for custom react components nested within a MapContainer

I have developed a custom control React component for a map as shown below: export const MapZoom = () => { const map = useMap() const handleButtonClick = () => { map.zoomIn() } return ( <IconButton aria ...

I'm encountering an issue with automatically updating content on a webpage

I am currently working on a webpage that refreshes its content automatically to display the most up-to-date data from the database. Here's the JavaScript code I'm using: setInterval(function() { $("#status").load('refresh.php'); }, ...

Everything runs smoothly when initiating the API call through npm start, but unexpectedly crashes upon attempting to

Here is an API call located at http://localhost:9000/testAPI. Within the bin/www file: var port = normalizePort(process.env.PORT || '9000'); app.set('port', port); Inside the routes/index.js file: var express = require('express&a ...