Wait for the promise of $ http before your next request

I am working on an angularJS application and this is my first website using this structure. In my application, I need to make a call to $ http inside a for loop. When in a loop before the next iteration I want to wait for an answer from my previous call. What is the best and easiest way to do this. I tried using callBack, $ q.all (), then in all these cases only the last request passes. Please, help.

Note. My API, which I call through $ http, cannot send requests to the queue.

Edit: I tried both approaches below: in both cases, only the last request succeeds. Can you tell me what's wrong, I'm here.

Approach 1:

var promiseArray=[]; for(var i=0;i<items.length;i++) { var promise=services.Post(items[i]); promiseArray.push(promise); } $q.all(promiseArray).then(data) { ... } 

Approach 2:

 var promises = []; for (var i = 0; i < items.length; i++) { var deffered = $q.defer(); var promise = services.Post(items[i]); promise.success(function(data) { deffered.resolve(data); }) promises.push(deffered); } 

var result = $ q.all (promises);

EDIT: 2 Service Code:

 Services.Post = function(lineItemId, submitUrl) { var url = (submitUrl) ? submitUrl : Services.serviceUrl; return $http.post(url, { "LineItemID": lineItemId }). success(function(data, status, headers, config) { Services.processResponse(data, status, headers, config); }). error(function(data, status, headers, config) { JL('Angular').error('Error response when calling Service ' + config); }); }; 
+5
source share
1 answer

You can use $q.when , which would promise $http , and when it is resolved, it calls the function inside .then

 $q.when(promiseObj).then(callback); 

If there are several promises, you can use $q.all , which will take an array of promises and call the then function when all the promises inside the function are resolved.

 $q.all([promiseObj1, promiseObj2]).then(callback); 

Update

I think your first approach is right only for a missed couple.

  • for A loop condition that creates an additional object that will be undefined
  • $q.all must have a function inside .then

the code

 var promiseArray=[]; for(var i=0; i < items.length - 1;i++) //<-- change from i<items.length { var promise=services.Post(items[i]); promiseArray.push(promise); } $q.all(promiseArray).then(function(data) //<-- it should be function in .then { //this will called after all promises get resolved. }); 
+5
source

All Articles