Ostap Lisovyj
Ostap Lisovyj

Reputation: 190

JavaScript, AngularJS - sending multiple simultaneous ajax calls

In my AngularJS application I have an array of parameters (some IDs, for example), which should be used as a parameters for an ajax call queue. The problem is that array might contain more than 600 items and if I just recursively make the ajax call using the forEach loop, the browser page eventually stops responding before each of the requests are resolved, since each of responses updates the view. Is there a technique, which could allow to send ajax requests, for example, by 5 requests at a time asynchronously, and only when those are finished, proceed the next 5?

Upvotes: 1

Views: 1278

Answers (3)

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

I think best solution would be to change the endpoint to allow an array of Id's, but I guess that is not an option. You can use promises to limit the number of simultaneous requests:

function chunkedAjax(idArray, index, limit) {
  if(index >= idArray.length) {
    return;
  }
  var index = index || 0;
  var limit = limit || 5;

  var chunk = idArray.slice(index, limit);
  var promises = [];

  angular.forEach(chunk, function(id) {
    var deferred = $q.defer();
    promises.push(deferred.promise);
    makeAjaxCall(id).then(function(response){
      deferred.resolve();
    });
  });

  $q.all(promises).then(function() {
    chukedAjax(idArray, index + limit, limit);
  });

}

This is a recursive function, so be warned. I would debug this heavily before putting into production.

You will also likely need to modify your makeAjaxCall function to return a promise if it does not already, or pass the promise object to it so that it can be resolved when the ajax call completes

Upvotes: 1

Davide
Davide

Reputation: 475

Yes!

Take a look on this module: https://github.com/caolan/async

Upvotes: -1

kenda
kenda

Reputation: 488

Take a look at $q.all(). This lets you execute a callback if multiple requests have finished. And therefore you are able to recursively execute a limited number of requests until all items are processed.

Upvotes: 1

Related Questions