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> }
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()
  • You might want to add that the await keyword is only valid in async functions – Henk Sep 20 '18 at 12:33
  • @Henk: True, but this dude specified his code in global scope, not inside a function. – goodvibration Sep 20 '18 at 13:22
  • Correct me if I'm wrong, but your code won't run in global scope – Henk Sep 20 '18 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. – goodvibration Sep 20 '18 at 13:59
0

//Use async before and //use await here var contract = await new web3.eth.Contract(HashABI, 'HashAddress')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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