AngularJS: loop POST requests and pass each index into related response

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.

Answers:

Answer

This will do the trick:

var params = [1, 2, 3],
    url,
    i,
    done = {};

for (i in params) {
    (function(p) {
        url = '/dir/'+ params[p];
        $http.post(url, {"some_request": "not important"}).
            success(function(response) {
                done[params[p]] = 'successful';
            });
    })(i);
}

Another option is closure.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.