0

I have a $watchCollection in angularJS that calls the function getBalance(addr) in the listener.

$scope.$watchCollection('settings',
  function() {
    for (i = 0; i < $scope.settings['accounts'].length; i++) {
      var bal = $scope.getBalance($scope.settings['accounts'][i]);
      console.log(bal);
    }
  }
);

The function getBalance is defined as follows:

$scope.getBalance = function(addr) {
  var balance;
  if ($scope.settings.contract !== null) {
    $scope.settings.contract.deployed().then(function(deployed) {
      return deployed.balanceOf(addr);
    }).then(function(res) {
       balance = res.toNumber();
       console.log(balance);
       return balance;
    }).catch(function(err) {
      console.log(err.message);
    });
  }
  return balance;
};

The problem is that in then, the balance variable is printed correctly however, in $watchCollection, return is undefined.

The problem should be because JS keeps executing without waiting for a result therefore the variable is read as undefined however, how do I have to change these two snippets of code in order to get the result when ready and append it to $scope.balance.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Afe
  • 167
  • 1
  • 10

1 Answers1

0

It looks like you're trying to change async code to sync code, which you can't really do. You need to carry the promise all the way through, in both.

Instead of setting balance to a variable and returning that variable, return the promise itself, then use then in your $watchCollection to get the value.

$scope.$watchCollection('settings',
  function() {
    for (i = 0; i < $scope.settings['accounts'].length; i++) {
      $scope.getBalance($scope.settings['accounts'][i])
        .then(bal => console.log(bal));
    }
  }
);

$scope.getBalance = function(addr) {
  if ($scope.settings.contract !== null) {
    return $scope.settings.contract.deployed().then(function(deployed) {
      return deployed.balanceOf(addr);
    }).then(function(res) {
       balance = res.toNumber();
       console.log(balance);
       return balance;
    }).catch(function(err) {
      console.log(err.message);
    });
  }

  return Promise.resolve(null);
};

Note, in functions that return Promises, make sure all pathways return a Promise or bad things will happen (hence the Promise.resolve(null)).

samanime
  • 25,408
  • 15
  • 90
  • 139