Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 396
0xtuytuy Avatar asked Apr 21 '26 01:04

0xtuytuy


1 Answers

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);.

like image 161
davidxxx Avatar answered Apr 23 '26 16:04

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!