Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/478.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未定义的值:angularjs$scope和web3.eth.getBalance_Javascript_Angularjs_Ethereum - Fatal编程技术网

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

Javascript 未定义的值:angularjs$scope和web3.eth.getBalance,javascript,angularjs,ethereum,Javascript,Angularjs,Ethereum,我只是尝试使用Web3API返回以太坊帐户的余额值,我希望在$scope中获得该值,以便在html中使用它。不幸的是,我总是得到一个未定义的值。我怀疑这是因为web3可能是异步的,但我不确定。这是我的密码: app.controller('mainController', function ($scope) { $scope.showBalance = function(){ web3.eth.getBalance("0xCc26fda641929192B2Fe96BBc

我只是尝试使用Web3API返回以太坊帐户的余额值,我希望在$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可能是异步的,但我不是 当然

你已经猜到了。

在这里:

    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(“这在+$scope.balance之外”)

我不知道web3.eth.getBalance是什么,但我认为这是一个承诺。如果是这样,回调函数中的代码将不会执行,直到承诺得到解决。同时,另一个代码继续执行。如果您在代码执行时单步执行代码,就可以看到这一点