Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using a $watchGroup to monitor their changes. Here is my controller code:

module Controllers {
    export class MyController {
        static $inject = ["$scope",'$http'];
        public TotalCurrent: any;
        public TotalPrevious: any;
        public diffPercent:any;
        constructor(
            private $scope: ng.IScope,
            private $http: ng.IHttpService,
        ) {
            this.$scope.$watchGroup(['myC.TotalCurrent', 'myC.TotalPrevious'], function (newVal, oldVal, scope) {
                if (newVal[0] != oldVal[0] && newVal[1] != oldVal[1] && newVal[0] != null && newVal[1] != null)
                    scope.myC.diffPercent = scope.myC.GetDifferencePercent(newVal[0], newVal[1]);
            });
                this.GetValuesFromAPI();
        }


        public GetValuesFromAPI() {
            this.TotalCurrent = null;
            this.TotalPrevious= null;


            this.$http.get("url1").then((result: any) => {
                if (result.value.length > 0) {
                    var TempCurrentTotal = 0;
                    for (var i = 0; i < result.value.length; i++) {
                        TempCurrentTotal += result.value[i].Val;
                    }
                    this.TotalCurrent = TempCurrentTotal;
                }

            });

            this.$http.get("url2").then((result: any) => {
                    if (result.value.length > 0) {
                        var TempPreviousTotal = 0;
                        for (var i = 0; i < result.value.length; i++) {
                            TempPreviousTotal += result.value[i].Val;
                        }
                        this.TotalPrevious= TempPreviousTotal;
                    }
                })
        }

        public GetDifferencePercent(current:any, last:any){
            var percentage = ((Math.abs(current - last) / last) * 100).toFixed(2);
            return percentage;
        }
    }
}

While the current method works well, I am concerned about potential performance issues with increasing API calls in the future. Is there an alternative approach to achieve this without relying on $watchGroup considering the response times of each API call and the impact on page speed when chaining them? Any suggestions would be appreciated.

Answer №1

Have you thought about running them simultaneously?

The usage of $q can be illustrated as follows:

const task1 = this.$http.get("endpoint1");
const task2 = this.$http.get("endpoint2");

this.$q.all([task1, task2]).then(outcomes => {
  // outcomes[0] contains the result of the first task, outcomes[1] holds the second.
});

You are able to incorporate the $q service in your class constructor.

Your callback will be executed once both tasks have finished processing. You may also handle errors by adding a catch statement.

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

Bringing JQuery into your Electron project through HTML

Working on some ElectronJS HTML coding and in need of using JQuery within the HTML. I've gone ahead and installed jQuery with npm install jquery. The question is, which file do I import to make use of JQuery? <!DOCTYPE html> <html lang="en" ...

Sort div elements based on checkbox filters

I have a set of checkboxes that I want to use for filtering purposes. <div class="filter"> <div class="checkbox"> <label><input type="checkbox" rel="canada"/>Canada</label> </div> <div class="chec ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...

VSCode is unable to locate the typeRoots type declarations

I have organized all the type definitions that will be used in my application into a single file. I created a folder named @types and an index.d.ts file that exports every interface/type needed. I updated my tsconfig.json to include the @types folder: { ...

The like count displayed in Django's AJAX feature is identical for every post

Having an issue with the ajax setup in my django twitter clone app. Every post's like count remains the same after clicking the like button, but it gets updated after a page refresh. I'm close to fixing it, but currently stuck. View: def add_li ...

I'm wondering why my socket.io emit isn't triggering a content update

While working on adapting the IBM angularjs tutorial here into a Yeoman angular-fullstack tutorial, I encountered a slight issue. In my version, when I vote on a Poll, the data does not refresh to display the results. I have tried extensively debugging it ...

The output is displayed on the console, but it cannot be stored in a variable

var x = ""; Promise.all(listOfItems).then(function(results) { for (let j in results) { var newitem = results[j]; x = newitem; console.log(`x: ${x}`); } }); The output on the console displays x: "val ...

The HTML div captured with html2canvas is incomplete

I am currently developing a meme editor website utilizing the html2canvas library available at Below is the HTML code for the div I aim to capture: <div class="container"> <div id="theUserMeme"> <div class=& ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...

Retrieve Cookie from a designated domain using Express

I am currently working on a React application that communicates with a Node/Express backend. To ensure the validity of requests, I am sending a cookie created by react-cookie from the React app to the Express app. To avoid issues related to naming conflict ...

JavaScript/jQuery Tutorial: Accessing the src attribute of images sharing a common class名

How can I extract the src values of images with the same class and display them in an empty div? For instance: <body> <img class="class1" src="http://www.mysite.com/img/image1.jpg" width="168" height="168" alt=""> <img class="class ...

What is the most efficient way to utilize a single Google Data Studio template across multiple accounts in a dynamic manner

I've been exploring different options on how to accomplish this: My dataset contains information on various clients, and I am interested in designing a custom Google Data Studio template for specific reports. Ideally, I would like the template to be ...

Troubleshooting a NextJs/TS problem with importing ESM modules

Click here for the Code Sandbox I'm currently in the process of transitioning some code to NextJS 11 / Webpack 5, including certain modules that now exclusively support ECMAScript Modules (esm). Prior to the upgrade, I could easily export all files ...

Transferring information from the main function to getServerSideProps

I've been facing challenges while trying to pass data from a function component to the getServerSideProps method in Next.js. As a beginner in learning Next.js, I am struggling to understand this concept. My approach involves using context from _app, b ...

Prevent automatic refreshing of React app on remote devices

My friend and I are collaborating on the development and testing of a React app simultaneously. He accesses the app from my machine using my IP address but encounters an issue where every time I save something in the code, the app reloads on both of our ...

What are the recommended methods or examples for implementing a scheduling calendar using JavaScript?

Here's a question that may be open to interpretation, and a red warning banner suggests it might be closed, but I'm not sure where else to turn for answers. I need an extremely lightweight display-only scheduling calendar for my application. Ess ...

Encountering challenges with reusing modules in Angular2

I am currently working on an angular2 website with a root module and a sub level module. However, I have noticed that whatever modules I include in the root module must also be re-included in the sub level module, making them not truly reusable. This is w ...

Finding out the RAM restriction of Docker for Mac through NodeJS

Understanding the Docker Limitation In our development setup, we utilize Docker for Mac to overcome the compatibility issues between Docker/Linux Containers and MacOS/Darwin/Unix. Docker for Mac employs a Linux virtual machine internally to run all contai ...

Struggling to get your HTML to Express app Ajax post request up and running?

I’m currently in the process of creating a Node Express application designed for storing recipes. Through a ‘new recipe’ HTML form, users have the ability to input as many ingredients as necessary. These ingredients are then dynamically displayed usi ...