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