角度等价于 jQuery deferred.always() 回调

Angular equivalent of jQuery deferred.always() callback

本文关键字:回调 always deferred 等价于 jQuery      更新时间:2023-09-26

我们可以在jQuery中使用.always()回调函数处理响应,无论响应是否成功。

在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?
您可以使用

Angular promise 的 finally 方法。

来自

$q服务的 final() 方法用于此目的:

$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
});

从回调返回承诺时的重要注意事项finally()

finally返回一个承诺,该承诺将使用相同的承诺来解决 履行价值或拒绝原因作为承诺。但是,如果callback 返回一个承诺,返回的承诺的解析将是 延迟,直到从回调返回的承诺完成。