Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After Angular.js $http request, call complete function regardless of success or failure of promise

How can I ensure that the complete() function will run regardless of the outcome of the $http call using the promise API provided with Angular.js?

$http({
    method: 'POST',
    url: submitUrl,
    data: $scope.data
})
.success(function(data) {
      // execute this code on success
})
.error(function(data) {
      // execute this code on error
})
.complete(function() {
  // execute this code regardless of outcome
});

One could use this to hide an AJAX spinner icon once the request is complete. You would want to hide the spinner regardless of the request outcome.

like image 912
Justin Avatar asked Jun 19 '13 01:06

Justin


1 Answers

I'm not the world's greatest expert in Angular.js but understand you can do as follows :

whatever.then(function() {
    // success code here
}, function() {
    // error code here
    return true; // return anything that's not undefined (and not a `throw()`) to force the chain down the success path at the following then().
}).then(function() {
    // "complete" code here
});

You are essentially forced to contrive something from one or more .then(), which is a $q promise's only method.

like image 175
Beetroot-Beetroot Avatar answered Oct 09 '22 10:10

Beetroot-Beetroot