gpt4 book ai didi

javascript - 如何从 "Promise"对象获取值

转载 作者:行者123 更新时间:2023-11-30 20:56:34 25 4
gpt4 key购买 nike

我开始学习以太坊和 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)
}

输出

it gives a promise object

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

最佳答案

您需要等待 promise 的值。您可以通过另一个 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 是无用的,在 的情况下,您应该调用 reject 并说明原因>如果(错误)

关于javascript - 如何从 "Promise"对象获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47601214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com