Subsequent ajax calls in angularJs

I want to make subsequent ajax calls in angularJs inside a service.

I tried something like this:

var requests = [
    {'url': 'call1'},
    {'url': 'call2'},
    {'url': 'call3'}
];

return $q.all([
    $http({
        url: requests[0],
        method: "POST"
    }).then( /*callback*/ ),
    $http({
        url: requests[1],
        method: "POST"
    }).then( /*callback*/ )
]);

But it does alla ajax in parallel. I need a way to make these calls subsequent, so after the first end, it calls the second ....

+4
source share
3 answers

You can bind promises:

  var requests =[{'url':'index.html'},
               {'url':'index.html'},
               {'url':'index.html'}];

function makeCall(n) {
  return $http({url:requests[n].url+"?n="+n,method:"GET"}).then(function(r) {
     if (n+1<requests.length) return makeCall(n+1);
  });
}
   makeCall(0);

http://plnkr.co/edit/1HdYUtHKe8WXAFBBq8HE?p=preview

+2
source

You can use async.eachSeries :

var requests = ['call1', 'call2', 'call3'];

function iterator(request, done) {
    $http({
        url: request,
        method: "POST"
    }).then(done);
};

async.eachSeries(
    requests,
    iterator,
    function (err) {
        // Done
    }
);

From readme :

eachSeries (arr, , ) , . . , .

  • arr - .
  • iterator(item, callback) - , . a callback(err), . , null.
  • callback(err) - , , .
+2

$http "then", $http

$http({...})
.then(function() {
  return $http({...});
 })
.then(function() {
  return $http({...});
});

, $http . "", "" , , , ajax.

: :

var requests = [
   {'url':'call1','method':'get'},
   {'url':'call2','method':'get'},
   {'url':'call3','method':'get'}
];

var promise = null;
angular.forEach(requests, function(details) {
  promise = $q.when(promise).then(function() {
    return $http(details);
  });
});

Plunker http://plnkr.co/edit/RSMN8WuPOpvdCujtrrZZ?p=preview. $q.when , promise null, then, .

+1

All Articles