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

3

我只是想使用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("This is inside") 能够正常工作并且我得到了正确的值。 但是 console.log("This is outside") 不能够工作,并且我得到了一个未定义的值。


1
我不知道web3.eth.getBalance是什么,但我认为它是一个promise。如果是这样的话,在回调函数中的代码将不会被执行,直到promise被解决。同时,其他代码将继续执行。如果您在执行代码时逐步执行,就可以看到这一点。 - jbrown
1个回答

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

getBalance()函数完成任务后,将执行回调函数function(err,res)。
回调函数声明不会阻塞程序。只有在被调用的函数完成其任务并返回一个Promise时,才能调用回调函数来通知其调用者任务结果。
因此,当调用getBalance()函数时,下一段执行的代码是:

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

但此时,回调函数还没有被调用。
只有当回调函数被调用时,$scope.balance = res.c[0] 才会被执行。

结论:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接