5

I have seen lots and lots of posts on this topic, and lots of web articles, but I remain stumped with my problem. I found this post very useful but my timeoutRequest() function is never being called.

I am using a promise with the timeout property of $http but the underlying HTTP request is not being cancelled. I think the promise itself is being resolved but the request is not cancelled.

My controller behaviours looks like this:

$scope.enquiriesSelected = function() {
    $scope.cancelHttpRequests();
    $location.path("/enquiries");
};

$scope.cancelHttpRequests = function () {
    console.log(canceller.promise.$$state);
    canceller.resolve("User cancelled");
    console.log(canceller.promise.$$state);
};

My HTTP request promise looks like this:

var canceller = $q.defer();

$scope.searchResultsPromise = $http({
        url: "/api/customers/customersearch",
        method: "POST",
        data: criteria,
        timeout: canceller.promise 
    })
    .success(function(data) {
        $scope.customerSearchResults = data;
    });

I have tried various methods to get this to work, including putting the canceller in the $scope.

I have been looking through the AngularJS source code and I find these lines:

if (timeout > 0) {
    var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (isPromiseLike(timeout)) {
    timeout.then(timeoutRequest);
}

function timeoutRequest() {
    jsonpDone && jsonpDone();
    xhr && xhr.abort();
}

However the execution path does not reach these lines when my promise is resolved. The xhr.abort() is never called and this is the only place in the AngularJS source code that aborts an HTTP request.

Inspecting with the console in F12 (Chrome) when trying to cancel the request reveals that the $$state of the promise changes from 0 to 1 so I'm reasonably sure that the promise is resolving. However in network traffic the HTTP request is not being cancelled. I cannot navigate to another page until the HTTP request is completed.

Can anyone help?

M

9
  • If your request taking long, I would probably make a boolean on server side, saying data is loaded/ready, and you can check every second if boolean is true, get data back. Two advantages here: user can cancel timer and avoid checking data ready, browser does not hang over. Commented Jun 2, 2015 at 9:09
  • I can't do that I'm afraid. I'm calling a service for which I don't have the source code. Commented Jun 2, 2015 at 9:11
  • Why do you save the promise to $scope.searchResultsPromise ? If you remove that, does that help? Commented Jun 4, 2015 at 16:31
  • The problem here is fairly simple theoretically but very complicated to implement, Imagine a client server architecture. Once the client is done sending request It's up-to server to timeout that request. So you have to code it on server side to allow a optional parameter with timeout milliseconds as value, If set the server will send error with timeout if that request processing takes more time than timeout. but even in this scenario, the communication time lapse is not factored in. The timeout set on client side only returns error for the promise and not handle response Commented Jun 4, 2015 at 17:07
  • 1
    To try to narrow this down, can you recreate this issue in a completely bare-bones Angular app, with one controller, only this http request being fired, and post the code + a link to it working (/not working) somewhere? Commented Jun 5, 2015 at 6:39

1 Answer 1

8
+100

What you are describing is actually the correct way of cancelling an $http request using the timeout property. I have created this Plunkr which showcases this behaviour being as close as possible to the code you have provided. You can see that when the "Submit request with timeout" button is clicked a request is submitted and the timeout promise is resolved after 100 msec (since the request returns so fast that you don't really have time to click something to cancel it):

$scope.requestWithTimeout = function() {
  $timeout(function(){canceller.resolve("User cancelled");}, 100);
  $scope.submitRequest();
}

The $http request error callback checks the status of the response and displays an appropriate error message, in which you can see that the request was actually cancelled after 100msec. You can also verify this by observing the request in the network tab of your browser's developer tools.

$scope.submitRequest = function() {
    // Reset the canceler promise
    canceller = $q.defer();
    $scope.status = 'Request submitted';
    var startTime = (new Date()).getTime();
    $http({ 
      url: 'style.css',
      method: 'GET',
      timeout: canceller.promise 
    })
    .success(function(data) {
      var endTime = (new Date()).getTime();
      $scope.status = 'Request response returned after ' + (endTime - startTime) + ' msec.';
    })
    .error(function(data, status) {
      var endTime = (new Date()).getTime();
      if(status === 0) {
        $scope.status = 'Request timed out after ' + (endTime - startTime) + ' msec.';
      } else {
        $scope.status = 'Request returned with error after ' + (endTime - startTime) + ' msec.';
      }
    });
  }

Hopefully you can use this as an example to find what is wrong with your code and correct it. Otherwise please create a Plunkr (or something similar) with the code that is not working so that I can help you further.

Sign up to request clarification or add additional context in comments.

10 Comments

Ok I will create a Plunkr and post the URL here. Thanks.
It's difficult because the HTTP request returns quite quickly; I'm on the hunt for a long-running service call.
Ok Christina, I have forked your Plunkr at plnkr.co/edit/zhhYjyIZdNdUjYxHFn5U. It's not the prettiest but it does demonstrate that it does in fact work, so I have to figure out what's different between my code and this sandbox code.
@serlingpa Are you sure it works? From what I can see the resource you are trying to access through the $http request is not accessible to the plunkr (due to CORS restrictions) so the request fails before the user has a chance to cancel it. That is not to say of course that it wouldn't work if the resource was accessible, it's just that in this particular case the request fails because of something else.
Hmm...you're right. BUT the network tab shows a status of cancelled rather than completed, so I'm hoping it works! I can't seem to find a large-ish PDF online avoiding CORS.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.