无法让Angularjs承诺正常工作

时间:2014-01-21 05:55:39

标签: javascript angularjs asynchronous promise

我知道在掌握承诺时我仍然缺少一些东西。我创建了这个jsfiddle以突出我的问题。我想倒数然后去哼!然而,繁荣将首先出现,然后是倒计时。我做错了什么/错过了什么?

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

1 个答案:

答案 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);

}

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