1

I have deployed a contract for producing hash :

Contract Hash
{   
  function sethash(string id)public pure returns(bytes32)
  {  
    return(keccak256(id));
  }
}

Now I am calling this function using web3js

    var Web3 = require('web3')
var web3 = new Web3('https://rinkeby.infura.io/infura_key')
var contract = new web3.eth.Contract(HashABI, 'HashAddress')
var number
number = contract.methods.sethash("123456789").call()
console.log(number)

But instead of giving me hash it is showing :

     Promise { <pending> }

3 Answers 3

1

call() is an asyncronous method. It has to wait until your node responds with the information which potentially take a lot of time, and therefore returns a promise so that JavaScript can keep on doing other things. To get the returned value out the promise, try the following code:

var Web3 = require('web3')
var web3 = new Web3('https://rinkeby.infura.io/infura_key')
var contract = new web3.eth.Contract(HashABI, 'HashAddress')

// Here, we pass a function to the promise using 'then()'
// to tell it how to act when it receives the information from your node
contract.methods.sethash("123456789").call().then(function(number) {  
    console.log(number)
})
1

Change this:

number = contract.methods.sethash("123456789").call()

To this:

number = await contract.methods.sethash("123456789").call()
4
  • You might want to add that the await keyword is only valid in async functions
    – Henk
    Commented Sep 20, 2018 at 12:33
  • @Henk: True, but this dude specified his code in global scope, not inside a function. Commented Sep 20, 2018 at 13:22
  • Correct me if I'm wrong, but your code won't run in global scope
    – Henk
    Commented Sep 20, 2018 at 13:31
  • @Henk: Yes, but you're wrong in the fact that it's not my code. When this dude adds await, he will get SyntaxError: await is only valid in async function, which he can then fix easily. I couldn't find a way to specify async in my answer, because the code at question did not include any function to refer to. Commented Sep 20, 2018 at 13:59
0
//Use async before and 
//use await here
var contract = await new web3.eth.Contract(HashABI, 'HashAddress')

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