我知道在掌握承诺时我仍然缺少一些东西。我创建了这个jsfiddle以突出我的问题。我想倒数然后去哼!然而,繁荣将首先出现,然后是倒计时。我做错了什么/错过了什么?
HTML
<div ng-app="" ng-controller="Controller">
<pre>{{output}}</pre>
</div>
JS
function Controller($scope, $q) {
$scope.output = "Boom Goes the Dynamite in... "
$scope.countdown = 10;
var defer = $q.defer();
defer.promise
.then(function() {
var timer = setInterval(function() {
$scope.output+="\n " + $scope.countdown;
$scope.$apply();
if ($scope.countdown === 0) {
clearInterval(timer);
}
$scope.countdown--;
},1000);
return true
})
.then(function(data) {
$scope.output+="\n " + "BOOM!!!!!";
});
defer.resolve();
}
答案 0 :(得分:2)
只有在异步操作完成后才能解析promise。因此,您需要将resolve
移至setInterval
:
function Controller($scope, $q) {
$scope.output = "Boom Goes the Dynamite in... "
$scope.countdown = 10;
var defer = $q.defer();
defer.promise.then(function() {
$scope.output += "\n " + "BOOM!!!!!";
});
var timer = setInterval(function() {
$scope.output += "\n " + $scope.countdown;
$scope.$apply();
if ($scope.countdown === 0) {
clearInterval(timer);
defer.resolve(); // <--- resolve here
}
$scope.countdown--;
}, 1000);
}