gpt4 book ai didi

javascript - 无法让 Angularjs promise 正常工作

转载 作者:行者123 更新时间:2023-11-29 14:53:52 25 4
gpt4 key购买 nike

我知道在把握 promise 时我仍然缺少一些东西。我创建了这个 jsfiddle 来突出我的问题。我正在尝试倒计时,然后开始 BOOM!然而,繁荣是先来的,然后是倒计时。我做错了什么/遗漏了什么?

http://jsfiddle.net/urAZ7/1/

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

最佳答案

您应该仅在异步操作完成后才 resolve 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);

}

http://jsfiddle.net/urAZ7/4/

关于javascript - 无法让 Angularjs promise 正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21250227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com