user14587589
user14587589

Reputation: 459

route is sending empty response

I have this controller

 const getBalance = async (address, network) => {
  const web3 = getWeb3Instance(network);
  const currentBalance = await web3.eth.getBalance(address);
  const formattedBalance = web3.utils.fromWei(currentBalance, 'ether');
  return formattedBalance
};

This is how I use it in the route:

 router.post('/getBalance', (req, res) => {
  const {address,network} = req.body
  try {
    res.status(200).send(controllers.getBalance(address,network))
  } catch (e) {
    res.status(404).send(`${e}`)
  }
});

When I console.log(formattedBalance) it logs the correct answer but in the response it is sending empty object {} and I don't know why. I'm using node.js with express and web3.

Any suggestions please?

Upvotes: 0

Views: 172

Answers (1)

Ilijanovic
Ilijanovic

Reputation: 14914

You have the word async infront of your function. An function has an different behaviour if you put async infront of it. It acts like an promise.

Did you tried console.log(controllers.getBalance(address,network))? In the browser you would see Promise { <pending> }

The problem is you sending an pending promise back.

Change it to this. You need to wait till the promise resolves

 router.post('/getBalance', async (req, res) => {
  const {address,network} = req.body
  try {
    let balance = await controllers.getBalance(address,network);
    res.status(200).send(balance)
  } catch (e) {
    res.status(404).send(`${e}`)
  }
});

Upvotes: 1

Related Questions