1

我开始学习 ethereum 和 web3js 并注意到 Web3js 上的一些功能是异步的。我想要实现的是获取钱包的帐户余额并将数据用于其他用途。我的代码如下

function getAccountBalance2(address){
            var wei, balance
            //address = document.getElementById("addy").value
            return new Promise(function(resolve, reject){
                web3.eth.getBalance(address, function(error, wei){
                    if(error){
                        console.log("Error with address");
                    }else{
                        var balance = web3.fromWei(wei, "ether");
                        var bal = resolve(balance);
                        //console.log(bal);
                        console.log(balance.toNumber());
                        return balance.toNumber();
                    }
                });
            });
        }

我正在尝试在下面的这个函数中使用返回值

function interTransfer(){
            var from, to, amount, fromWallet, toWallet
            from = document.getElementById("from").value
            to = document.getElementById("to").value
            amount = document.getElementById("amount").value

            if(isWalletValid(from) && isWalletValid(to)){
                fromWallet = getAccountBalance2(from);
                toWallet = getAccountBalance2(to);
            }else{
                console.log("Something is wrong")
            }

            console.log(fromWallet + " "+ toWallet)
        }

输出

它给出了一个承诺对象

我如何获得实际值并在interTransfer()函数中使用它

4

1 回答 1

1

您需要等待承诺的值。您可以通过另一个then调用来执行此操作,并且——为了避免一个请求必须等待前一个请求完成—— Promise.all

function interTransfer(){
    // ...
    promise = Promise.all([getAccountBalance2(from), getAccountBalance2(to)])
        .then(function ([fromWallet, toWallet]) {
            console.log('from wallet', fromWallet, 'to wallet', toWallet); 
        });
    // ...
    return promise; // the caller will also need to await this if it needs the values
}

或者,使用async函数和await关键字:

function async interTransfer(){
    // ...
    [fromWallet, toWallet] = 
        await Promise.all([getAccountBalance2(from), getAccountBalance2(to)]);
    console.log('from wallet', fromWallet, 'to wallet', toWallet); 
    // ...
    return [fromWallet, toWallet]; // caller's promise now resolves with these values
}

请注意,return回调getBalance中的 没有用,您可能应该rejectif(error).

于 2017-12-01T20:53:13.277 回答