与jQuery等效的角度延迟。always()回调

时间:2022-08-23 11:34:03

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

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

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?

2 个解决方案

#1


2  

You can use the finally method of Angular promises.

你可以用角承诺的最后一种方法。

#2


1  

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

$q服务的finally()方法用于:

$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()回调返回承诺时的一个重要通知:

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.

最后返回一个承诺,这个承诺将以与承诺相同的履行价值或拒绝理由得到解决。但是,如果回调返回一个承诺,返回承诺的解析将被延迟,直到从回调返回的承诺完成为止。

#1


2  

You can use the finally method of Angular promises.

你可以用角承诺的最后一种方法。

#2


1  

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

$q服务的finally()方法用于:

$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()回调返回承诺时的一个重要通知:

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.

最后返回一个承诺,这个承诺将以与承诺相同的履行价值或拒绝理由得到解决。但是,如果回调返回一个承诺,返回承诺的解析将被延迟,直到从回调返回的承诺完成为止。