1

I'm using node.js to execute a simple JavaScript script that tests access to the rinkeby blockchain using an infura endpoint. specifically, it is checking the balance of my address.

In the code if I invoke:

console.log(web3.eth.getBalance(address));

it only returns the Promise i.e.

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

If on the other hand I call:

console.log(web3.eth.getBalance(address, function (error, result) { }));

it returns both the Promise and the address balance i.e..

Promise {
  _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }
18750000000000000000

I don't really understand why it prints out the Promise at all. I simply want it to return the value only i.e. 18750000000000000000

How can I achieve this and do I really need to specify the function (error, result) { } optional parameter to all the web3 function calls just to get it to return me the data I need?

thanks

2 Answers 2

1

try with something along the lines of:

const get_eth_balance = async (web3, account) => {

  const balance = await web3.eth.getBalance(account);

  return balance;
};

get_eth_balance(web3, account);

The main keywords here being the async/await which make the code look much saner than it would by using callbacks.

2
  • firstly, thank you for your prompt and informative response: your code only serves to print out: "getting account balance: [object Promise]" not the actual value I'm expecting. Am I missing something else here? Also, does the async/wait approach mean I can dispense with the much more verbose and hard-to-read Promise.then() syntax? Commented Feb 19, 2018 at 15:08
  • 1
    yes, you can also use it like web3.eth.getBalance(account).then( balance => {console.log(balance)} ) Commented Feb 19, 2018 at 15:26
2

If I remember correctly the current web3 version (v1.0) doesn't support synchronous operations. If you want synchronous functions (without promises or async/await) you could install the previous version by doing the following:

npm install [email protected]

const Web3 = require('web3')
const web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io'))
const address = '0x966e42aA4E7368818517a93656362C30d8E4d5fE'
const balance = web3.eth.getBalance(address)
console.log(balance.toNumber())

Your Answer

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

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