Executing callback functions after numerous asynchronous calls have been completed

Is there a method to delay the execution of a specific line of code until multiple API calls have all returned?

Typically, I follow this pattern:

APIService.call(parameter).then(function(response) {
   // Do something
   callBack();
});

This approach works well as callBack() is only triggered after the response from APIService.call().

However, what if I have three separate API calls like this:

$scope.var1 = APIService.call1(parameter)
$scope.var2 = APIService.call2(parameter)
$scope.var3 = APIService.call3(parameter)

If I want my callback function to be invoked only after all three calls have completed, with the delay being determined by the slowest call, how can this be achieved without nesting then statements and maintaining asynchronous behavior for all three calls?

Is there a solution for this scenario?

Answer №1

If you are utilizing AngularJS, one approach is to employ $q.all. You could try the following method:

var requests = [];

requests.push(ServiceA.getData(param));
requests.push(ServiceB.getData(param));
requests.push(ServiceC.getData(param));

$q.all(requests).then(function (results) {
    // access response from each request
    $scope.data1 = results[0];
    $scope.data2 = results[1];
    $scope.data3 = results[2];
    performActions();
})

Answer №2

If you're looking to handle multiple promises in AngularJS, the $q.all() method is perfect for the job. Simply provide it with an array of promises that you need to resolve, and it will return a new promise that resolves once all the original promises are resolved.

$q.all([
  APIService.call1(parameter),
  APIService.call2(parameter),
  APIService.call3(parameter),
]).then(function(data) {

   //TODO: something...
});

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

Tips for incorporating dynamic URLs in Next.js

In my current project using nextjs, I am dealing with fetching images via an API. Right now, I am receiving the "Full image path" (for example, "https://myurl.com/image/imagename.jpg") without any issue. However, I need to figure out how to fetch the image ...

What is the process for configuring SSL in node.js and express.js?

I'm currently working on setting up my application to run in HTTPS mode. Despite thinking that my configuration is correct, the page isn't loading at all. Within my SSL folder, I have the following files: credentials.js my-ca.pem my-cert.pem my ...

Determine whether the response from a jQuery AJAX call is in JSON format or binary. If it is found to be binary, proceed

I am currently using ajax to retrieve and download an xlsx file from a PHP script. The script has two possible types of responses: JSON format if there are any warnings preventing the download (such as incorrect parameters), or the xlsx binary stream if ev ...

Despite the presence of data, MongoDB is not returning any values

I am currently working on a code that utilizes $geoNear to find the closest transit stop to a given GPS coordinate. The issue I am facing is that the result sometimes returns undefined, even though I have confirmed that the data exists in the STOPS collect ...

Code for refreshing content using AJAX

I'm looking for AJAX code to set a value in a session. For instance: $_SESSION['verif_code'] I want to generate a random number and assign it to this session. I need some AJAX code to refresh this random number function and set the value ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...

Utilize React-router to display child components on the webpage

Recently, I've encountered some challenges with this code. I have a component that takes in a child as a prop, which is meant to serve as the foundation for all the pages I am hosting. Base.jsx : import React from 'react'; import PropTypes ...

NodeJS controller function to generate and send a response

I'm facing an issue with my controller method where I am unable to send a response to the user, even though the value is displaying in the console. Below is my code snippet: const hubHome = (req,res) => { const hubId = req.params.hubId; fetch ...

Trouble with Webpack compiling SCSS files

I'm struggling with setting up webpack to bundle my js react components, js modules, and compile my .SCSS files to css. Despite multiple attempts, I keep encountering errors. Below is an excerpt from my webpack.config.js: const webpack = require(&a ...

Please input only 0s and 1s into the designated field

How can I modify this code to only accept 0 and 1 in the input field, while also adding spaces after every 4 digits? Currently, it accepts all digits. I'm struggling with creating a pattern that restricts it to just 0 and 1. document.getElementById(&a ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...

Tips for modifying the icon of a div with a click event using vanilla JavaScript

My goal is to create a functionality where clicking on a title will reveal content and change the icon next to the title. The concept is to have a plus sign initially, and upon clicking, the content becomes visible and the icon changes to a minus sign. C ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Load a file in Express.js after the page has finished loading

I need some assistance with my web app that involves reading and writing files. The issue I am facing is when I try to load the results page, it gives an error stating that it cannot load the coverage file. As far as I understand, this happens because th ...

How can I implement "named parameters" in a unique AngularJS filter that I am creating?

While creating a unique Angular filter, I aim to implement something similar to "named arguments" in Python. This would mainly be for boolean options to avoid passing a confusing sequence of true/false values. If I were only considering calling from plain ...

Header reference differs from the document referrer

this is the request header: GET / HTTP/1.1 Host: localhost:3002 Connection: keep-alive sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96" sec-ch-ua-mobile: ?0 User-Agent: ...

The browser is unable to load the local JSON file due to an XMLHttpRequest error

I have been attempting to import a json file into a table, after conducting thorough research I finally discovered some solutions on how to achieve this. However, when trying to implement it in Chrome, I encountered the following error: XMLHttpRequest ...

Swapping out data within a container

I've been experimenting with creating a hangman game using JavaScript and HTML. However, I'm facing an issue where clicking on a letter doesn't replace the "_" placeholder. var myList=["Computer","Algorithm","Software","Programming","Develop ...

A SyntaxError was caught due to an unexpected token '<' in the constants.js file when using react and vite

I'm trying to display a button in the sidebar with a name and an icon. I've been iterating through the list of categories, which are imported from the 'constants.js' file located in the utils folder. However, instead of getting the desi ...

Automatically append version number to requests to avoid browser caching with Gulp

When deploying my project, I utilize gulp to build the source files directly on the server. In order to avoid caching issues, a common practice is to add a unique number to the request URL as explained in this article: Preventing browser caching on web app ...