AngularJS allows for the execution of several asynchronous requests to a single API function, each with unique parameters

How can I asynchronously call 3 independent API methods so that as soon as any one of them has completed, I can work with the response without waiting for the others to finish? I am looking for a solution similar to System.Threading.Tasks in C#.

var promise1 = $http.get("/api/city/boston");
promise1.success(function(name) {
   console.log("Your city is: " + name);
});

var promise2 = $http.get("/api/city/newyork");
promise2.success(function(name) {
   console.log("Your city is: " + name);
});

var promise3 = $http.get("/api/city/chicago");
promise3.success(function(name) {
   console.log("Your city is: " + name);
});

Answer №1

It seems that your code may not function as expected. The variables you are using are promise1, promise2, promise3, but when resolving them, you have only utilized promise.resolve.

Additionally, instead of "success," it is recommended to use "then." For example:

$http.get(url).then(function(response){
    //perform actions with the response data
});

Answer №2

When working with Angular, use $q.race() to handle the first completed task and $q.all() for when all tasks are completed.

To simplify requests, consider creating a function to map out request promises.

Remember that using success() is now deprecated.


For example:

const getCityData = (city) => {
   return $http.get(`/api/city/${city}`).then(res => res.data)
}

const requestPromises = ['boston','newyork','chicago'].map(getCityData);

$q.race(requestPromises).then(data => console.log('First one completed ', data));

$q.all(requestPromises).then(dataArray => console.log('All completed', dataArray ))
                       .catch(err => console.log('Something failed', err)

Ensure you have injected the $q service in the controller or service where this code is executed.

Read more about $q in the Angular documentation

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

Obtaining the data value from a style applied to a div element in an E-commerce platform like MyShop

I have recently started using MyShop for my online store at www.myshop.com. The programming language they use is quite different from what I am used to. For example, the total price in the basket.html script is displayed using the following code: <spa ...

Having trouble with filtering an array using the some() method of another array?

When utilizing the code below, my goal is to filter the first array by checking if the item's id exists in the second array. However, I am encountering an issue where the result is coming back empty. dialogRef.afterClosed().subscribe((airlines: Airli ...

Discovering the Authentic Page upon Completion of Load using PhantomJS

I am facing an issue while automatically downloading a theme on Wordpress using PhantomJS. The problem arises because the page is not fully evaluated even after it appears to be done loading. When trying to interact with elements on the page, such as clic ...

Displaying NodeJS error messages directly in the main HTML file

After creating a form using NodeJs and implementing input validations that display errors when users enter incorrect values, I encountered an issue where the errors appear on a new blank page instead of within the main HTML file itself with stylish formatt ...

Bypassing the "Your connection is not private" error in NodeJS + Express with fetch() using Javascript

Presently, I have a setup with a NodeJS + ExpressJS client-side server that communicates with the back-end server via API calls. However, every time I make a call, I need to manually navigate to the URL of the API back-end server and click on Advanced -> ...

What is the best approach to implement pagination in the UI-Bootstrap Typeahead Directive?

In my current Angular Project, I am utilizing the UI-Bootstrap's Typeahead Directive for a specific purpose. However, I am encountering an issue when dealing with a large amount of similar data using this directive. It seems that displaying only the ...

AngularJS showcasing data in a visually appealing layout

Successfully connected API and displaying data, but now encountering an issue with formatting the data into a table. When using ng-repeat="item in items", if used within a tr tag, only one row is shown. If used within a tbody tag, it repeats the tbody. He ...

Analyzing vast datasets from contrasting perspectives

Looking for a way to compare two different data storages that contain the same data. The data in question is: const object1 = { "name": "John", "age": "30", "height": "180 cm", "stand ...

Holding off on routing the pathName through the router until the next-page-transitions have been completed

In my current setup, I have two distinct elements at play. Using the code snippet below: className={router.pathname.startsWith("/pagename") ? "menu-active" : ""} I am able to apply the menu-active class to the pagename naviga ...

What is the best way to create a test for a program that relies on standard output?

I am currently focusing on enhancing test coverage for this particular file. 'use strict' /** * Retrieves the logging configurations in use * * @param {String} name Name of the logger. Should correspond ...

Display additional javascript code for expanding a marquee

Currently, I am working on a stock ticker project using JavaScript. It's progressing well, and now I am focusing on adding a "show more" button to style the ticker. The button should be placed outside of the marquee. When clicked, it will expand the m ...

What could be causing my reducer function to return 'NaN'?

I have been working on updating the total quantity in my shopping cart. Utilizing hooks useSelector, I retrieve the state from Redux and access all the items currently in my cart. By using reduce function, I am able to calculate the total quantity of items ...

Updating user attributes as an administrator using the Cognito SDK

Currently, I am in the process of developing an Angular application and I aim to integrate authentication using AWS Cognito (my experience with AWS is fairly limited). So far, I have successfully incorporated features such as sign-up, sign-in, sign-out, MF ...

Having trouble extracting data from JSON object with an AJAX request

I have written some code to fetch JSON data from a servlet using an Ajax call. When the success function is executed, I am able to see the response in the console as Object: [{"userId":"dfeterter"}]. However, I am facing difficulty in accessing the value ...

When using jQuery to enable contenthover on divs, they will now start a new line instead of

I've been working on achieving a layout similar to this, with the contenthover script in action: Mockup Draft Of Desired Look However, the result I'm getting is different from what I expected, it can be seen here. The images are not aligning co ...

Recursive sorting and parsing of JSON data with multiple levels

I'm new to using recursion in JavaScript and need some guidance to understand it better. I have a JSON data structure with multiple levels of nested "subcategories". const STORE_CATEGORIES = [{ "Id":"1", "Name":"One Parent", ...

Error message "Script start is missing" found in install.json for socket.io-php package

I am looking to develop a .io game that integrates with some PHP APIs, and I have been attempting to run the following files: install.json: { "name" : "workerman/phpsocket.io", "type" : "library", "keywords": ["socket.io"], "homepage": ...

If a div element includes a specific text, then update that portion of the text without altering the value of any variables

Need help removing text without affecting variables Attempting to translate a specific line with JQuery Looking to change text only, leaving the content within the strong tag intact $('.content-box__row div:nth-child(3)').text('') ...

Ways to simultaneously apply fade in and fade out effects using CSS

body { background-image: url("background.jpg"); background-attachment: fixed; font-family: 'Roboto', sans-serif; color: #333333; } #container { height: 1000px; } /* HEADER WITH NAVIGATION BAR AND LOGIN OPTION */ #head { position: abso ...

Selecting options from a pop-up menu

I've created a dropdown menu with what seems to be correct code. However, there are no errors showing up, but the selected item from the menu is not alerting as expected. Here is the jsfiddle link $(document).ready(function () { // This function ...