0

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.

1
  • you need to us await and warpped those inside an async function oder user .then(res => ….)
    – Majd TL
    Nov 5, 2021 at 20:33

1 Answer 1

2
// 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);
7
  • Hey thanks, but I get the following: var balance1 = await web3.eth.getBalance(address1); ^^^^^ SyntaxError: await is only valid in async function
    – JDS
    Nov 5, 2021 at 23:26
  • 1
    declare your surrounding function as async then. I edited the answer to show how. Alternatively, depending on what you need, you can work with promises.
    – phaze
    Nov 6, 2021 at 0:02
  • Hey thanks for the update. Unfortunately I still get await logBalance(); ^^^^^ SyntaxError: await is only valid in async function. Bear in mind I'm running this code in the top level of my app.js node application server.
    – JDS
    Nov 6, 2021 at 5:53
  • 1
    If you're running this in your react project it makes more sense to go with promises. You don't want your main thread to be waiting on calls. Use a state for the balance: web3.eth.getBalance(address1).then(setBalance).catch(console.error);
    – phaze
    Nov 6, 2021 at 8:04
  • 1
    yeah, the answer doesn't have anything to do with react. You'll have to read up on async calls and promises to understand it better.
    – phaze
    Nov 7, 2021 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.