未定义的值:angularjs $ scope和web3.eth.getBalance

时间:2017-02-03 20:28:45

标签: javascript angularjs ethereum

我只是想使用web3 api返回以太坊帐户的余额值,我想在$ scope中获取该值,以便我可以在我的html中使用它。不幸的是我总是得到一个未定义的值。我怀疑这是因为web3可能是异步的,但我不确定。这是我的代码:

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();
    });
});

基本上console.log(“这是在里面”)有效,我确实得到了正确的值。 但是console.log(“This is outside”)没有,我得到一个未定义的值。

1 个答案:

答案 0 :(得分:2)

  

不幸的是,我总是得到一个未定义的值。我怀疑是的   因为web3可能是异步的,但事实并非如此   肯定的。

你猜对了。

这里:

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

函数(err,res)是getBalance()函数完成任务时执行的回调函数。
回调函数声明没有阻塞。它仅在被调用函数完成其任务时执行,因此返回一个允许调用回调函数的promise,以通知其调用者任务的结果。
因此,当调用getBlance()函数时,下一个执行的代码是:

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

但是目前还没有调用回调函数 那只有在调用回调函数时才会这样  $scope.balance = res.c[0]已执行。

结论:

您应该删除console.log("This is outside:" + $scope.balance);