我有这个html代码
<body ng-app="myModule">
<div ng-controller="myController">{{text}}</div>
</body>
还有这个js代码
var myModule = angular.module('myModule', []);
myModule.controller('myController', ['$scope', 'Database', function($scope, Database) {
Database.first()
.then($scope.text = 'first')
.then(Database.second())
.then($scope.text = 'second')
.then(Database.third())
.then($scope.text = 'third');
}]);
myModule.factory('Database', ['$window', '$q', function($window, $q) {
return {
first: function() {
var deferred = $q.defer();
setTimeout(function() {deferred.resolve();alert('ei')},4000);
return deferred.promise;
},
second: function() {
var deferred = $q.defer();
setTimeout(function() {deferred.resolve()},4000);
return deferred.promise;
},
third: function() {
var deferred = $q.defer();
setTimeout(function() {deferred.resolve()},4000);
return deferred.promise;
},
}
}]);
(在这里找到http://jsfiddle.net/C5gJr/44/)
然后我想知道为什么 deferred 没有等到我问的时间就解决了。我使用此结构是为了不在另一个函数完成之前启动一个函数,并且它的工作方式如下(此处使用 setTimeout)。
另一个(次要)问题
.then($scope.text = 'first')
.then(Database.second())
为什么当我只是填充一个变量时,.then 函数仍然有效?
提前致谢:)
杰拉德
最佳答案
你的错误是你使用了then
错误。应该是:
Database.first()
.then(function() {
$scope.text = 'first';
})
.then(function() {
return Database.second();
})
.then(function() {
$scope.text = 'second'
})
.then(function() {
return Database.third()
})
.then(function() {
$scope.text = 'third'
});
演示:http://plnkr.co/edit/NGYPiLdUGBzzvVHFFBWy?p=preview
再来一次。这个
.then($scope.text = 'first')
不正确。 then
希望您在其中传递一个函数。所以应该是:
.then(function() {
$scope.text = 'first'
})
关于javascript - Angularjs,Promise 写得不好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21731378/