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); }); };