Within my AngularJS application, I am utilizing a $watchCollection function to call the getBalance(address) function within 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 implementation of the getBalance function is 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;
};
An issue arises where the balance variable is correctly printed in the 'then' method but returns undefined within $watchCollection.
This discrepancy may be due to JavaScript continuing execution without waiting for a result, leading to the variable being read as undefined. How can I modify these code snippets to ensure that the result is retrieved when ready and appended to $scope.balance?