Search code examples
javascriptangularjsajaxpromisees6-promise

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?


Solution

  • 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