Reputation: 7601
I'm using $q
in a method to get an array of objects. I also have a method called getItems
which makes use of this promise (all
).
I use all
a second time at the bottom, to do stuff with $scope.list
. The code has to be wrapped inside all().then(function() { ... }
so it only triggers when $scope.list
ready.
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
}
This works...almost. Sometimes the first all
finishes first and sometimes the second one. So sometimes $scope.list
has the objects and sometimes it's empty.
How to create a new promise that only triggers when all
fetches the array of objects?
Upvotes: 3
Views: 243
Reputation: 5605
You can do it like so:
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
}
If you return a promise in a function you can chain a .then
to it, so now your getItems
will return the promise from all()
, once this is fulfilled your code will continue
Upvotes: 7