Search code examples
javascriptweb3js

Promise { <pending> } in Web3


I need something help.. I'm trying to make an async request but the response is a Promise { <pending> }

This is my code

const getBalance = async (adress) => {
  try {
    let wei = await web3.eth.getBalance(address);
  } catch (err) {
    console.error(err);
  }
};

let balanceWallet = getBalance(address);
console.log(balanceWallet);

So when I run my code to debug it returns Promise { <pending> } I don't know what's wrong in my code


Solution

  • getBalance is an async function :) JS does not allow us to use async/await on the program top level but we can use then/catch to get promise result)

    You just have to use (but before u have to change getBalance function and return promise there)

    const getBalance = (adress) => web3.eth.getBalance(address);
    
    getBalance(address)
    .then(balanceWallet => {
      console.log(balanceWallet)
      // some logic with result
    })
    .catch(error => /** handle an error **/ )
    

    I hope it helps! Enjoy programming!