search

Home  >  Q&A  >  body text

Problems with multiple then promises in angular.js

<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?

黄舟黄舟2796 days ago585

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:22:03

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

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:22:03

    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.

    reply
    0
  • Cancelreply