2

In my application, I have a service called 'pendingRequests' that keeps track of my http requests. I configured my $httpProvider to use this service.

The purpose of this service is to give me the ability to cancel ALL pending http requests occurring in ANY controller.

Here is the code:

app.service('pendingRequests', function($rootScope, $q) {
  var pending = [];
  this.get = function() {
    return pending;
  };
  this.add = function(request) {
    pending.push(request);
    //console.log("Pending Requests(before):" + pending);
  };
  this.remove = function(request) {
    angular.forEach(pending, function(p , key) {
      if(p.url == request.url) pending.splice(key, 1);
    });
   // console.log("Pending Requests(after):" + pending);
  };
  this.cancelAll = function() {
    if(typeof pending !='undefined'){
    angular.forEach(pending, function(p) {
      p.canceller.resolve();
    });
    pending.length = 0;
    }
  };
});
app.config(function($httpProvider){
$httpProvider.interceptors.push(function($q, pendingRequests){
    return {
        'request': function (config){
            var canceller = $q.defer();
            pendingRequests.add({
                url: config.url,
                canceller: canceller
            });
            config.timeout = canceller.promise;
            return config || $q.when(config);
        },
        'response': function (response){
            pendingRequests.remove(response.config);
            //pendingRequests remove request
            return response;
        }
    }
  });
});

The service is canceling the requests as intended. However, the next request submitted is delayed as if it is still waiting for another request to complete.

What is causing this delay?

Big D
  • 23
  • 3
  • It sound like maybe the underlying XHR is not getting abort()'ed. Browser's will make a max of N [number of connections](http://stackoverflow.com/a/985704/398606) to a given server, which is why I'm guessing you experience the delay (it's waiting for previous requests to finish). Do you see any evidence of the request not really being canceled in your server logs or browser's web inspector? Have you tried another browser? – Sunil D. Mar 07 '15 at 00:06
  • I am seeing the request being canceled [link](http://i.imgur.com/JQzgdQ3.png) http://i.imgur.com/JQzgdQ3.png . The canceled request usually takes over a minute. If you look at the time it takes on the request after the canceled one, you can see it takes over a minute. It normally just takes milliseconds. – Big D Mar 07 '15 at 00:20

0 Answers0