Search code examples
javascriptethereumsolidityweb3js

Call solidity function from JavaScript got [object promise]?


I have a very simple Solidity function in a contract MyContract.

function getCount() view public returns (uint) {
    return myArray.length;
}

And the following JavaScript which uses web3 prints [object Promise] instead of the count number?

MyContract.deployed().then(i => {
  var count = i.getCount.call();
  console.log(count); // print [object Promise]
})

Solution

  • As per your code:

    MyContract.deployed().then(i => {
      var count = i.getCount.call();
      console.log(count); // print [object Promise]
    })
    

    MyContract.deployed() will deploy contract to eth network. It will take time to miners verify and add contract code to blockchain. After successful completion of this process then() will invoke.

    And coming to i is deployed contract object, using i variable you can access contract.

    i.getCount.call().then(val =>{ console.log("Value")}) //instance.getCount().call will returns promise. So 
    

    call() is async method i.e it will not wait for complete the step. When you got the data at that time then() will invoke.

    Or simply call instance.getCount() your execution will pause until you get the result.

    My option is use then()