Problems with multiple then promises in angular.js
黄舟
黄舟 2017-05-16 13:20:03
0
2
614
<p ng-app="MyApp">
  <p ng-controller="MyController">
    <label for="flag">成功
      <input id="flag" type="checkbox" ng-model="flag" /><br/>
    </label>
    <p ng-cloak>
      {{status}}
    </p>
    <hr/>
    <button ng-click="handle()">点击我</button>
  </p>
</p>
<script>
  angular.module("MyApp", [])
    .controller("MyController", ["$scope", "$q", function ($scope, $q) {
      $scope.flag = true;
      $scope.handle = function () {
        var deferred = $q.defer();
        var promise = deferred.promise;

        if ($scope.flag) {
          deferred.resolve("you are lucky!");
        } else {
          deferred.reject("sorry, it lost!");
        }
        promise.then(function (result) {
          result = result + "you have passed the first then()";
          $scope.status = result;
          return result;
        }, function (error) {
          error = error + "failed but you have passed the first then()";
          $scope.status = error;
          return error;
        }).then(function (result) {
          alert("Success: " + result);
        }, function (error) {
          alert("Fail: " + error);
        })
      }
    }]);
</script>

Why when my $scope.flag is false, the first then is error and the second then is success. If I want to change it, how do I change it?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
Peter_Zhu
promise.then(function (result) {
      result = result + "you have passed the first then()";
      $scope.status = result;
      // return result;
      return $q.resolve(result);
    }, function (error) {
      error = error + "failed but you have passed the first then()";
      $scope.status = error;
      // return error;
      return $q.reject(error);
    }).then(function (result) {
      alert("Success: " + result);
    }, function (error) {
      alert("Fail: " + error);
    })
给我你的怀抱

Each .then returns a new promise. After the new promise executes the failed code, it will resolve the return value of the function currently passed into .then. So the second one executed is success.

It’s useless to talk too much about this problem. Just look at the promise source code and you’ll understand it at once.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template