I am trying to use AngularJS to execute multiple http POST requests and I need to create an object of successfully finished requests - something like this:
var params = [1, 2, 3],
url,
i,
done = {};
for (i in params) {
url = '/dir/'+ params[i];
$http.post(url, {"some_request": "not important"}).
success(function(response) {
done[params[i]] = 'successful';
});
}
I would like to get an object with all successful request like this:
done = {1: 'successful', 2: 'successful', 3: 'successful'};
But obviously due to asynchronous nature of http requests I only get
done = {3: 'successful'};
because when the http requests are returning responses, the loop already finished and is at it's last value.
Order of those requests is not important and I don't want to chain them (executing them asynchronously should be faster). How do I pass that loop index into those responses? Thank you.
This will do the trick:
Another option is closure.