as3rdaccount
as3rdaccount

Reputation: 3951

How to pass multiple $http promise under $q

I have a bunch of urls I want to make GET calls one after another and then join the return data for each url.

I am using the following code to combine multiple promises and then passing it under $q.all.

var urls = _.map(urlArray, function(pUrl) {
  var promise_obj = $http.get(pUrl);
  return promise_obj;
});

$q.all(urls)
  .then(function(responses) {
      ctrl.points = _.reduce(responses, function(data, response) {
        if (elem == undefined) {
          return data.concat(response.data);
        } else {
          return data.concat(response.data[elem]);
        }
      }, []);

    }
  });

But this does not work since the urls variable passed to $q.all is empty. I am assuming the reason is $http.get call is asynchronous so byt the time I am calling the $q.all the value of urls is empty.

The issue is I can have as many urls so I would not want to chain the responses. Any idea how I can get this working?

Upvotes: 1

Views: 105

Answers (1)

user1364910
user1364910

Reputation:

I've modified your code slightly, here's a jsBin (albeit using $timeout instead of $http) to showcase the changes made.

But seeing as how $timeout(func) and $http.get both return a promise (and I've done what you're doing multiple times in the past with an array of $http.get's), I would look into why the urls/urlArray end up being undefined when being passed into $q.all().

I believe the error lies somewhere before you reach $q.all. Possibly a rejected promise.

Docs for $q.all:

Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.

Try adding a .catch in the promise chain.

Upvotes: 0

Related Questions