javascripthtmlweb3jsbinance-smart-chain

web3 [object, Promise] error that .then and await does not work


    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
...
    <script>
      const web3 = new Web3('https://bsc-dataseed1.binance.org:443');
      const version = web3.version.api;
      const burnAddress = "0x000000000000000000000000000000000000dead";

      //jQuery pull of contractABI from getAddress
      function pullData() {
        getAddress = $('input[name="contractAddress"]').val();
        getJSONString = 'https://api.bscscan.com/api?module=contract&action=getabi&address=' + getAddress + '&apikey' + API_KEY;
        $.getJSON(getJSONString, function(data) {
          contractABI = JSON.parse(data.result);
          //document.getElementById("json").innerHTML = "JSON: " + JSON.stringify(contractABI);
          myContract = new web3.eth.Contract(contractABI, getAddress);
          decimals = tokenContract.methods.decimals().call(); // promise error
          document.getElementById("decimals").innerHTML = "Decimals: " + decimals;

        });
        document.getElementById("addy").innerHTML = "Address: " + getAddress;
       }
     </script>

Seems like no matter what I do I can never get a number to populate, and JSON.stringify() does not show anything either.

Yes a form input is passed in calls pullData() Then that address pulls an ABI (that works) I can create a new contract instance, I can pull as many [object, Promise] as the <p id's> can handle on any of "my methods" from read the docs (also yes, the console.log(decimals) works too, but none show numbers ever in HTML. I did search here, what am I missing?

Code above is from my vanilla test HTML page.


Solution

  • I don't know much about this API, but I think you need to change this:

    decimals = tokenContract.methods.decimals().call(); // promise error
    document.getElementById("decimals").innerHTML = "Decimals: " + decimals;
    

    To something like this:

    tokenContract.methods.decimals().call().then(decimals => {
      document.getElementById("decimals").innerHTML = "Decimals: " + decimals;
    });
    

    Perhaps reading up on Promise.then() might help you out. After that, look up async/await.