我听说$ q和promise对于同步编程非常有用。
我希望我的第二个函数在我的第一个超时函数之后运行。所以基本上我想要第一个函数在我的第二个函数运行之前先完成运行
我的代码是:
<head>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="myClick()">Click Me!</button>
</div>
<script type="text/javascript">
angular.module('myApp', [])
.controller('myCtrl',['$scope', '$timeout', '$q', function($scope, $timeout, $q){
$scope.functionOne = function(){
return $q(function(resolve, reject){
$timeout(function(){
alert("dean");
}, 3000);
})
};
$scope.functionTwo = function(){
alert("armada");
}
$scope.myClick = function(){
var promise = $scope.functionOne();
promise.then(function(){
$scope.functionTwo();
}, function(){
alert("fail");
})
};
}]);
</script>
</body>
Plunker:https://plnkr.co/edit/6hJF4mxrCQ17XXA43eUl?p=preview
答案 0 :(得分:2)
承诺已创建,但从未解决。但是you don't need it at all! $timeout
已经返回一个承诺:
$scope.functionOne = function(){
return $timeout(function(){
alert("dean");
}, 3000);
};
答案 1 :(得分:1)
在我看来,做你想做的事情的更好方法是:
$scope.functionOne = function(){
var defer = $q.defer();
$timeout(function(){
defer.resolve({data:""}); // or defer.reject(data)
}, 1000);
return defer.promise;
};