wait for $http response before continuing with angular.forEach loop


Solution – recursive function with $q.

If you really must make one request at a time, then you’ll have to use something other than Angular.forEach.

What about something like this (you will need to inject $q): (i.e. recursive function)

function doWhateverWithAll(someArray) { // Mark which request we're currently doing var currentRequest = 0; // Make this promise based. var deferred = $q.deferred(); // Set up a result array var results = [];

makeNextRequest(); function makeNextRequest() { // Do whatever you need with the array item. var postData = someArray[currentRequest].blah; $http.post('some/url', postData) .then( function (data){ // Save the result. results.push(data); // Increment progress. currentRequest++; // Continue if there are more items. if (currentRequest < someArray.length){ makeNextRequest(); } // Resolve the promise otherwise. else { deferred.resolve(results); } }); // TODO handle errors appropriately. } // return a promise for the completed requests return deferred.promise; }

Then, in your controller/service, you can do the following:

doWhateverWithAll($scope.someArray)
.then(function(results){
  // deal with results.
});

Happy Coding Smile

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s