angularjs承诺/超时:条件超时

时间:2019-02-13 15:13:02

标签: javascript angularjs timeout angular-promise

那么只有.then()达到5后才有可能达到$scope.counter吗?

这里是JSFiddle

以某种方式使用Promise破坏了我的观察者-仅在调整窗口大小时适用。所以我想知道如果没有Promises

是否可以做到
<div ng-app="myApp">
    <div ng-controller="myController">
    <div>some{{message}}</div>
    <div>counter: {{counter}} sec</div>
    </div>
</div>

(function(){

var myApp = angular.module('myApp', []);

myApp.controller('myController', function($scope, $timeout){

    //time
    $scope.counter = 0;
    $scope.message = "";

    //timer callback
    var timer = function() {
        $scope.counter++;
        if ($scope.counter > 5) {
            return;
        }
        $timeout(timer, 1000);
    }

    $timeout(timer, 2000).then(function() {
        $scope.message="body once told the world was gonna roll me";
    });       

});

})();

1 个答案:

答案 0 :(得分:1)

$timeout不会返回任何类型的Promise,但是,如果您真的想使这项工作脱离诺言,则可以执行以下操作:

var defer = $q.defer();
var timer = function() {
    $scope.counter++;
    if ($scope.counter > 5) {
        defer.resolve(true);
        return;
    }
    $timeout(timer, 1000);
}

$timeout(timer, 2000);
defer.promise.then(function() {
    $scope.message="body once told the world was gonna roll me";
});   

柱塞:Google Photos APIs

在不了解更多代码的情况下,如果两个超时值可以相同,建议不要使用$interval而不是$timeout。还会问为什么不只在if ($scope.counter > 5)条件内设置您的信息。