0

I call an http service, loop through the results and each item acts as the key for another http-call.

What's the best way to do that?

I guess calling $http from within another $http call does not work as the outer $http-loop may just exit before the inner $http calls have finished?

// pseudo code:

$http.get(url).then((response) ->
  foreach response.data as item
        $http.get(item.url).then((response) ->
          foreach response.data as item
        )
  return result
)

Doesn't really work, right?

2
  • 1
    I am not sure but what is your concern, but all http calls would be made irrespective of loop or function exiting. If you want some type of coordination, then you need to provide more details. Commented Aug 22, 2013 at 15:12
  • If you bind to $scope inside the then, it shouldn't matter when the response is returned. Commented Aug 22, 2013 at 15:13

2 Answers 2

2

This psuedo code will work fine. The then is a callback for the async operation. See promises in angular for more detail.

You are correct that the flow of the code execution will continue, but the callback (then) will still fire when the response is returned.

So, this means that if you are binding to $scope inside the then, all will be fine and the data will bind into the model.

Sign up to request clarification or add additional context in comments.

Comments

1

This works fine, but you need to collect the sub-responses in an array or object and return $q.all(sub-responses) to ensure the caller waits for them to resolve.

Sticking to your pseudo-code I think it looks like:

$http.get(url).then((response) ->
 var r = [];
 foreach response.data as item
    r.push($http.get(item.url))
 return $q.all(r).then((subs) -> foreach ...)
 )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.