3

I tried web3.js 1.0.0-beta.

I found in document method web3.utils.fromWei(value, 'ether') convert the wei to ether. In new version getBalance method work as asynchronous. how can I get the value from getBlance then passed as Big number

I tried

web3.utils.fromWei( web3.eth.getBalance("0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1"),'ether');

But got error!

1
  • 2
    This isn't really an Ethereum question. You use web3.js's asynchronous functions the same way you use any asynchronous functions in JavaScript.
    – user19510
    Commented Jun 21, 2018 at 18:16

3 Answers 3

6

I wrote a simple Web3.js sample which fetches the balance of an Ethereum address: https://github.com/shawntabrizi/ETH-Balance

This is using Web3.js 0.2x.x, but the only difference here for Web3.js 1.0 is to change web3.fromWei to web3.utils.fromWei.

Thus by simply making that one small change, you can get the call to start working:

web3.eth.getBalance(address, function (error, wei) {
    if (!error) {
        var balance = web3.utils.fromWei(wei, 'ether');
        console.log(balance + " ETH");
    }
});

You can also read my blog post which discusses how to make Web3.js work asynchronously with JavaScript Promises.

2

Another way is to use promise instead of call back:

web3.eth.getBalance(address).then(result => web3.utils.fromWei(result,"ether"))
1

If you have used async, then you need to add await as well:

 const getBalance = async () => {
    const balance = web3.utils.fromWei(
      await web3.eth.getBalance(address),
      "ether"
    );

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .