Okan Kocyigit
Okan Kocyigit

Reputation: 13431

Angular equivalent of jQuery deferred.always() callback

We can handle response with .always() callback function in jQuery whether response is success or not.

Is there an equivalent of this type of usage in AngularJS?

//jQuery
$.get( "test.php" ).always(function() {
  alert( "$.get completed with success or error callback arguments" );
});

//AngularJS
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    //success
  }, function errorCallback(response) {
    //error
  });

//how can i handle always?

Upvotes: 1

Views: 736

Answers (2)

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19110

The finally() method from $q service used for this:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    //success
}).catch(function errorCallback(response) {
    //error
}).finally(function() {
    //Callback method
    //Executed always, no matter of success or fail
});

An important notice when returning promises from finally() callback:

finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished.

Upvotes: 1

Bergi
Bergi

Reputation: 664936

You can use the finally method of Angular promises.

Upvotes: 2

Related Questions