AngularJS: request POST requests and pass each index to the corresponding response

I am trying to use AngularJS to execute multiple HTTP POST requests, and I need to create a successfully completed request object - 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 the successful request as follows:

 done = {1: 'successful', 2: 'successful', 3: 'successful'}; 

But obviously, due to the asynchronous nature of the HTTP requests, I get

 done = {3: 'successful'}; 

because when HTTP requests return responses, the loop is already completed and has the last value.

The order of these requests is not important, and I do not want to bind them (executing them asynchronously should be faster). How to pass this loop index into these answers? Thanks.

+4
source share
1 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 closing.

+6
source

Source: https://habr.com/ru/post/1487667/


All Articles