我只是试图使用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(“这是外”)没有,我得到一个未定义的值...
我不知道web3.eth.getBalance是什么,但我认为它是一个承诺。如果是这样,那么回调函数中的代码将不会被执行,直到promise被解析。同时,其他代码继续执行。如果您在执行代码时逐步完成代码,您可以看到这一点 – jbrown