为什么$q.当在Angular中后跟$q.拒绝时.js会导致成功

Why does $q.when followed by $q.reject in Angular.js result in success?

本文关键字:js 成功 Angular 当在 为什么 拒绝      更新时间:2023-09-26

在 Angular 中.js 使用 $q 时,为什么这段代码不:

 $q.when("test")
   .then($q.reject("error"))
   .then(
     function(v) {
       $scope.result = "Success: " + v;
     },
     function(e) {
       $scope.result = "Failure: " + e;
     }
   )

调用错误回调?

在 jsfiddle 中:http://jsfiddle.net/c9tv6kz7/1/

根据文档

then(successCallback, errorCallback, notifyCallback) – 不管 当承诺已经或将被解决或拒绝时,然后调用一个 结果后立即异步异步回调 可用。回调使用单个参数调用: 结果或拒绝原因。此外,通知回调可能是 在 承诺已解决或拒绝。

此方法返回一个新的承诺,该承诺通过以下方式解析或拒绝 成功回调的返回值,错误回调(除非 值是一个承诺,在这种情况下,它用 使用承诺链接在该承诺中解决)。它还通知 通过通知回调方法的返回值。承诺不能 从通知回调方法中解析或拒绝。

我们真正关心的路线是

此方法返回一个新的承诺,该承诺通过以下方式解析或拒绝 成功回调、错误回调的返回值

每次你打电话给then $q.when你就是在创造一个新的承诺。即使第一个承诺被拒绝,第二个承诺也没有。第二个没有被拒绝,因为你的 successCallback 和 errorCallback 的返回值没有拒绝它。

更简单的答案是:

$q.reject("error")

创建一个由您的$q.when().then()调用的新承诺对象。

这真的不会像你想的那样。 $q.reject("error")返回一个带有 then 函数的对象。

查看文档中的方法部分:

promiseB = promiseA.then(function(result) {
  // success: do something and resolve promiseB
  //          with the old or a new result
  return result;
}, function(reason) {
  // error: handle the error if possible and
  //        resolve promiseB with newPromiseOrValue,
  //        otherwise forward the rejection to promiseB
  if (canHandle(reason)) {
   // handle the error and recover
   return newPromiseOrValue;
  }
  return $q.reject(reason);
});

你看到他们是如何做的then(function () { return $q.reject(reason); })这与你的原始大不相同。

查看新小提琴

当我这样做时,我解决了一个错误:

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$q', function($scope, $q) {
  $q.when("test")
    $q.reject('Failed!')
    .then(
      function(v) {
        $scope.result = "Success: " + v;
      },
      function(e) {
        $scope.result = "Failure: " + e;
      }
    )
}]);

http://jsfiddle.net/emporio/67db45f9/3/

如果我删除$q.reject('Failed!'),它将解析为 .then()。