1

Consider 3 calls to the same API method. They are independent of each other. How can I call them asynchronously so that as soon as any one of them has completed I can do something with the response instead of waiting for the other ones to complete? Looking for something similar to System.Threading.Tasks available 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);
});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
abcdspd42
  • 13
  • 5
  • 1
    I'm pretty sure the code you've provided will do exactly that. – wbadart Sep 22 '19 at 17:12
  • The AngularJS framework will do those operations in parallel if the back-end supports it. BTW the `.success` method has been [removed from the AngularJS framework](https://stackoverflow.com/questions/35329384/why-are-angularjs-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg Sep 22 '19 at 17:33

2 Answers2

0

Your code will not work. Your variables are promise1, promise2, promise3. But while resolving you have used only promise.resolve.

Secondly, instead of success you should use then. Like below

$http.get(url).then(function(response){
    //do something with the response.
 });
Sagar Agrawal
  • 639
  • 1
  • 7
  • 17
0

Use angular's $q.race() for the first one completed and $q.all() for all completed.

You can simplify the requests also using a function and mapping the request promises array.

Also note that success() is deprecated


Something like:

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)

Make sure you inject $q service in controller or service where you run this.

$q docs

charlietfl
  • 170,828
  • 13
  • 121
  • 150