I have encountered an issue where I am returning a promise from a function that is part of a $q.all
array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to update the view with new data.
Here is the working code:
var vm = this;
var loadingGames = $q.defer();
var loadingPlayers = $q.defer();
var getGames = function() {
playersService.getGames({
playerId: playerId
}).$promise.then(function(data) {
vm.games = data;
loadingGames.resolve();
});
};
var getPlayers = function() {
playersService.getPlayers({
playerId: playerId
}).$promise.then(function(data) {
vm.players = data;
loadingPlayers.resolve();
});
};
$q.all([loadingGames.promise, loadingPlayers.promise]).then(function() {
populateOptions(vm.games);
vm.tableParams.reload();
});
var init = function() {
getGames();
getPlayers();
}
init();
The problem here is evident: loadingGames
was already resolved on page load, so depending on it will not fetch any updated data:
var updateStatus = function() {
getGames();
loadingGames.promise.then(function() {
populateOptions(vm.games);
vm.tableParams.reload();
});
};
I attempted another approach by modifying the code as follows, but faced an error "
TypeError: Cannot read property 'then' of undefined
" while trying to execute updateStatus
:
var updateStatus = function() {
getGames().then(function() {
populateOptions(vm.games);
vm.tableParams.reload();
});
};
How can I ensure that future promises for getGames()
are resolved correctly so that updateStatus()
receives updated data?
Update: I made another attempt using a callback, but unfortunately, the functions within the callback were never executed.
var updateStatus = function() {
getGames(function() {
populateOptions(vm.games);
vm.tableParams.reload();
});
};