MattDionis
MattDionis

Reputation: 3616

Why does this promise not behave as expected?

I'm struggling to understand why after calling updateStatus() I see 'promise resolved' logged to the console, but not 'refreshGames'. How is the promise resolved if the code inside refreshGames() never runs?

var refreshGames = function() {
  console.log('refreshGames');
  var defer = $q.defer();
  playersService.getGames({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.games = data;

    return defer.promise;
  });
};

var updateStatus = function() {
  $q.all([refreshGames.promise]).then(function() {
    console.log('promise resolved');
    populateOptions(vm.games);
    vm.tableParams.reload();
  });
};

Upvotes: 2

Views: 43

Answers (2)

Guilherme
Guilherme

Reputation: 1990

Because your function refreshGames returns nothing, it should return the promise and the defer must be resolved, like this:

var refreshGames = function() {
  console.log('refreshGames');
  var defer = $q.defer();
  playersService.getGames({
    playerId: playerId
  }).$promise.then(function(data) {
    vm.games = data;

    defer.resolve(data);
  });

  return defer.promise;
};

and in the $q.all you just do refreshGames()

Upvotes: 2

Jaromanda X
Jaromanda X

Reputation: 1

refreshGames.promise is undefined - there's no code anywhere that creates this property on refreshGames

any non-promise in $q.all is promisified and effectively equivalent to Promise.resolve(n) (or however you do that with $q

so, your $q.all is essentially

$q.all([undefined]).then(function() {
   ...
});

and thus gets executed immediately

Upvotes: 2

Related Questions