链接 .then()-调用:无法识别拒绝

Chaining .then()-calls: Rejection not recognized

我很难理解承诺的概念(angularjs)。

我认为我可以定义一个 return 是承诺的函数。此承诺的使用者可以使用它,并且可能 return 一些数据或承诺。

但是这个简单的示例表现出乎意料:第一个 .then() 调用 return 是拒绝,而第二个 then() 调用执行成功函数。

angular.module('myexample', []).controller('Ctrl', ['$scope', '$q',
  function($scope, $q) {
    $scope.sdfsdf = "";
    $scope.action = function() {
      $('#msg').html("");
      $.Deferred().resolve()
        .then(function(response) {
          $('#msg').html("error during processing of data!");
          return $q.reject('my-failure-reason');
        })
        .then(
          function(data) {
            $('#msg').html($('#msg').html() + "<br>success: " + data);
          },
          function(data) {
            $('#msg').html($('#msg').html() + "<br>failure: " + data);
          }
        );
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body ng-app="myexample">
  <div ng-controller="Ctrl">
    <button ng-click="action()">Go!</button>
    <div id="msg"></div>
  </div>
</body>

我查看了类似的问题,但我找不到我的方法与接受的答案中的方法之间的区别 (e.x。this one)

这是因为您以 $.Deferred().resolve() 开始您的链,这是一个 jQuery 承诺。 jQuery 承诺不符合 Promises/A+ 标准(尚未!),因此无法正确处理错误。有关详细信息,请参阅 this question and answer

简单的解决方案就是不要将您的代码包装在 jQuery 延迟中。如果你想要一个空的已解决的承诺,你可以使用 Angular 的 $q.when() 代替。

angular.module('myexample', []).controller('Ctrl', ['$scope', '$q',
  function($scope, $q) {
    $scope.sdfsdf = "";
    $scope.action = function() {
      $('#msg').html("");
      $q.when() // not jQuery
        .then(function(response) {
          $('#msg').html("error during processing of data!");
          return $q.reject('my-failure-reason');
        })
        .then(
          function(data) {
            $('#msg').html($('#msg').html() + "<br>success: " + data);
          },
          function(data) {
            $('#msg').html($('#msg').html() + "<br>failure: " + data);
          }
        );
    };
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body ng-app="myexample">
  <div ng-controller="Ctrl">
    <button ng-click="action()">Go!</button>
    <div id="msg"></div>
  </div>
</body>