【问题标题】:How to get a value from a "Promise" object如何从“Promise”对象中获取值
【发布时间】:2018-05-16 00:29:59
【问题描述】:

我开始学习 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() 函数中使用它

【问题讨论】:

标签: javascript promise ethereum web3js web3


【解决方案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
}

请注意,getBalance 回调中的return 是无用的,您可能应该在if(error) 的情况下调用reject

【讨论】:

  • 从不知道 promise 的 .then 到使用 async/await 是一个很大的飞跃:p
猜你喜欢
  • 2021-07-29
  • 2015-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 2021-09-25
  • 2017-03-18
  • 1970-01-01
相关资源
最近更新 更多