web3js – How to Troubleshoot Javascript Web3 Account Balance Promise/Async Issues

javascriptweb3js

I am having difficulty wrapping my head around how to just get the balance:

// Testing:
const address1 = "0xA5...";

var balance1 = web3.eth.getBalance(address1);
console.log(balance1);
balance2 = 0;
balance2 = web3.eth.getBalance(address1, (err, wei) => { balance = web3.utils.fromWei(wei, 'ether'); return balance; });
console.log(balance2);

But I only get back "promises":

Promise { <pending> }
Promise { <pending> }

How do I get back these variable values at the "top level" of my code? Or does everything need to be wrapped in an async function somehow? Quite confused… any help appreciated.

Best Answer

// Testing:
const address1 = "0xA5...";

var balance1 = await web3.eth.getBalance(address1);
console.log(balance1);
var balance2 = await web3.utils.fromWei(await web3.eth.getBalance(address1))
console.log(balance2);

since web3 calls are mostly async / return promises.

Edit: If you're using await in a function, your outer function needs to be declared as async.

const address1 = "0xA5...";

const logBalance = async () => {
    var balance1 = await web3.eth.getBalance(address1);
    console.log(balance1);
};

await logBalance();

Or use promises (this runs asynchronously)

web3.eth.getBalance(address1).then(console.log);
Related Topic