如何从“承诺”获得价值。目的

编程入门 行业动态 更新时间:2024-10-24 12:32:35
本文介绍了如何从“承诺”获得价值。目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I started learning ethereum and web3js and noticed some functions on Web3js are asynchronous. What i want to achieve is get the account balance of a wallet and use the data for something else. My code below

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(); } }); }); }

而我试图在下面的此函数中使用返回值

and i am trying to use the returned value in this function below

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()函数

How do i get the actual value and use it in the interTransfer() function

推荐答案

您需要等待承诺的值。您可以使用另一个然后调用,并且-为避免一个请求不得不等待上一个请求完成-- Promise.all :

You need to await the promised values. You can do this with another then call, and -- to avoid one request having to wait for the previous one to finish -- 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 关键字:

Or, with an async function and the await keyword:

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 }

请注意,<$ c $ getBalance 回调中的c> return 是没有用的,您可能应该使用以下命令调用 reject if(error)的原因。

Note that the return in the getBalance callback is useless, and you should probably call reject with a reason in the case of if(error).

更多推荐

如何从“承诺”获得价值。目的

本文发布于:2023-10-25 08:09:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526415.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目的   价值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!