【发布时间】:2013-11-23 21:00:19
【问题描述】:
所以看来我仍然没有正确理解承诺。下面是一个控制器,它通过资源获取一系列帖子。它应该首先获取数组,然后将数组作为单独的函数加载到作用域中。这不起作用,因为 promise 中的所有函数似乎仍然被同步调用。例如,名为getPosts() 的函数需要超过一秒,因为我在服务器上插入了延迟来模拟延迟。但是尽管占用了一秒钟,promise 中的所有其他函数都是同步调用的。任何线索都会很棒。
var postController = myapp.controller('postController', function ($q, $rootScope, $scope, Post, $routeParams) {
var new_posts = []
$scope.new_post_count = 0
var getPosts = function () {
$scope.refreshing = true
var params = $routeParams
Post.query(params).
$promise.then(
function (response) {
$scope.refreshing = false;
new_posts = response
$scope.new_post_count = new_posts.length - $scope.posts.length
},
function (response) {
alert('Snap! ' + response.status)
}
)
}
$scope.refreshPosts = function () {
$scope.posts = new_posts
$scope.new_post_count = 0
}
/* all the functions below (marked 1, 2, 3) within the promise still called synchronously.
I thought they would wait until the previous function has finished? */
var defer = $q.defer()
defer.promise
.then(function () {
// 1
console.log('calling getposts')
getPosts()
})
.then(function () {
// 2
console.log('calling refresh posts')
$scope.refreshPosts()
})
.then(function () {
// 3
console.log('calling interval')
$interval(function () {
getPosts()
}, 7000, 0
)
})
defer.resolve()
【问题讨论】:
-
all the functions in the promise still seems to get called synchronously.all the functions是什么?谢谢 -
我试图澄清这个问题。我希望它现在更有意义
标签: javascript angularjs promise q