Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for $http promise before the next request

I'm working on an angularJS app and this is my first website using this framework. In my app i've a need to make a $http call inside a for loop. With in the loop before the next iteration I want to wait for the response from my previous call. What is the best and simple way to do this. I've tried using the callBack, $q.all(), .then in all of these only the last request is going through. Please help.

Note: My API that i'm calling through $http can't queue requests.

Edit: I've tried both the below approaches, in both of the cases only the last request is being made successfully. Can you tell me what is wrong i'm doing 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);

    });
};
like image 252
Ajay Srikanth Avatar asked Apr 23 '15 18:04

Ajay Srikanth


1 Answers

You could use $q.when which would take promise of $http & when it gets resolved it call the function inside .then

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

If there are multiple promise then you could use $q.all which would accept array of promise & called then function when all promise inside the function gets resolved.

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

Update

I think your 1st approach is right only missed couple thing

  1. for loop condition, which does create an extra object which would be undefined
  2. $q.all should have function inside .then

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.
});
like image 64
Pankaj Parkar Avatar answered Oct 12 '22 22:10

Pankaj Parkar