2017-02-03 66 views
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(“这是内部”)的作品,我也得到正确的值。 但console.log(“这是外”)没有,我得到一个未定义的值...

+1

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

回答

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()功能已经完成了它的任务执行的回调函数。
回调函数声明没有被阻塞。它仅在被调用函数完成其任务时执行,因此返回一个允许调用回调函数以通知调用者任务结果的承诺。
所以当被调用函数getBlance(),下执行的代码是:

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

但就在这个时候,回调函数没有被勾起。
只有在调用回调函数时才执行 $scope.balance = res.c[0]

结论:

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