AngularJS: loop POST requests and pass each index

2020-04-10 00:07发布

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.

1条回答
▲ chillily
2楼-- · 2020-04-10 00:40

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.

查看更多
登录 后发表回答