Search code examples
javascriptangularjsethereum

Undefined value: angularjs $scope and web3.eth.getBalance


I am simply trying to return the Balance value of an ethereum account using the web3 api, I would like to get that value in the $scope so I could use it in my html. Unfortunately I always get a value is undefined. I suspect it is coming from the fact that web3 might be asynchronous but I am not sure. Here is my code:

app.controller('mainController', function ($scope) {
    $scope.showBalance = function(){
        web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc37DB5B451Cb9A8c", 
            function(err, res){
                $scope.balance = res.c[0]
                console.log("This is inside:" + $scope.balance);
            });

        console.log("This is outside:" + $scope.balance);
    };

    angular.element(document).ready(function () {
        $scope.showBalance();
    });
});

Basically the console.log("This is inside") works and I do get the right value. But the console.log("This is outside") doesn't and I get an undefined value.


Solution

  • Unfortunatly i always get a value is undefined. I suspect it is comming from the fact that web3 might be asynchronous but I am not sure.

    You have guessed.

    Here :

        web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc37DB5B451Cb9A8c", 
            function(err, res){
                $scope.balance = res.c[0]
                console.log("This is inside:" + $scope.balance);
            });
    
        console.log("This is outside:" + $scope.balance);
    

    the function(err,res) is the callback function executed when the getBalance() function has finished its task.
    A callback function declaration is not blocking. It is only executed when the called function has finished its task and so return a promise that allows to invoke the callback function to notify its caller of the result of the task.
    So when getBlance() function is invoked, the next executed code is :

    console.log("This is outside:" + $scope.balance);.
    

    But at this time, the callback function has not been still invoked.
    That is only when the callback function is invoked that $scope.balance = res.c[0] is executed.

    Conclusion :

    you should remove console.log("This is outside:" + $scope.balance);.