Search code examples
javascriptangularjspromisetimeout

AngularJS Promise is not being cancelled when timeout called


I am trying to implement a simple timeout functionality to my promise. Goal is if I do not receive response say in 1 second, then the request should be cancelled i.e. code should not wait for the response neither should the code after success be called. This seemed to me very simple code but I don't know why its not working. Following is my code:

var canceler = $q.defer();
var timeoutPromise = $timeout(function() {
    canceler.resolve(); //abort the request when timed out
    console.log("Timed out");
    }, 1000);
$http.put(PutUrl, PurDataObject, {timeout: canceler.promise})
  .then(function(response){
        // control should never come here if the response took longer than 1 second
});

Any help is appreciated. I am using AngularJS v1.5.5.


Solution

  • No need to use $q.defer() as the $timeout service already returns a promise:

    var timeoutPromise = $timeout(function() {
        console.log("Timed out");
        return "Timed out";
    }, 1000);
    
    $http.put(PutUrl, PurDataObject, {timeout: timeoutPromise})
      .then(function(response){
            // control should never come here if the response took longer than 1 second
    });