<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>
為什麼當我$scope.flag為false的時候第一個then走是error而第二個走的是success,要改的話改怎麼改
给我你的怀抱2017-05-16 13:22:03
每個.then都會回傳一個新的promise。新的promise執行失敗的程式碼後,會resolve目前傳入.then的函數的回傳值。因此第二個執行的是success。
這問題說多了也沒用,自己看promise源碼,一下就清楚了。