Tuesday 15 July 2014

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


I am trying to use AngularJS to execute several HTTP POST requests and one of the successful requests Need to create an object - something like this:

  var params = [1, 2, 3], url, i, done = {}; For (in the parameter) {url = '/ dir /' + parameter [i]; $ Http.post (url, {"some_request": "not important"}) success (work) [done] [paraem [i]] = 'successful';}); }   

I would like to get an object with all successful requests like this:

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

But clearly because of the asynchronous nature of http requests, I only get

  done = {3: 'successful'};   

Because when the responses to HTI requests are returning, the loop has already ended and is at its final value.

Order of those requests is not necessary and I do not want to chain them (execution should be asynchronous) How do I pass those loops into those reactions? Thank you.

This will do the trick:

  var params = [1, 2 , 3], URL, I, did = {}; For (in the parameter) {(function (p) {url = '/ dir /' + params [p]; $ http.post (url, {"some_request": "not important"}). Response) {done [param [p]] = 'successful';});}) (i); }   

Another option is closed.

No comments:

Post a Comment