我开始学习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()
函数
答案 0 :(得分: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
无效,如果reject
,您可能应该使用if(error)
来调用result.getScanRecord().getBytes();
。