我在方法中使用$q
来获取对象数组。我还有一个名为getItems
的方法,它使用了这个承诺(all
)。
我在底部第二次使用all
来处理$scope.list
的内容。代码必须包含在all().then(function() { ... }
内,因此只有在$scope.list
准备就绪时才会触发。
var all = function() { return $q.all([service.getAllItems()]) }
var getItems = function() {
all().then(function(value) {
$scope.list = JSON.parse(value)
}, function(reason) {
$scope.result = reason
})
}
getItems()
all().then(function() {
// do stuff with $scope.list
}
这几乎可以。有时第一个all
首先完成,有时第二个完成。所以有时$scope.list
有对象,有时它是空的。
如何创建仅在all
获取对象数组时触发的新承诺?
答案 0 :(得分:7)
你可以这样做:
var all = function() { return $q.all([service.getAllItems()]) }
var getItems = function() {
return all().then(function(value) {
$scope.list = JSON.parse(value)
}, function(reason) {
$scope.result = reason
});
}
getItems().then(function() {
// do stuff with $scope.list
}
如果你在函数中返回一个承诺,你可以将.then
链接到它,所以现在你的getItems
将从all()
返回承诺,一旦完成,你的代码将继续