angular.js中promise多个then的问题
本文介绍了angular.js中promise多个then的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<div ng-app="MyApp">
<div ng-controller="MyController">
<label for="flag">成功
<input id="flag" type="checkbox" ng-model="flag" /><br/>
</label>
<div ng-cloak>
{{status}}
</div>
<hr/>
<button ng-click="handle()">点击我</button>
</div>
</div>
<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,要改的话改怎么改
解决方案
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);
})
这篇关于angular.js中promise多个then的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文