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
.