0

What happens when we use "callback" as a keyword in a function ? And when do we need to use it ? and what happens if we do not use it ? For example in the following JavaScript code:

function signPayment(recipient, amount, nonce, contractAddress, callback) {
  var hash = "0x" + ethereumjs.ABI.soliditySHA3(
    ["address", "uint256", "uint256", "address"],
    [recipient, amount, nonce, contractAddress]
  ).toString("hex");

  web3.personal.sign(hash, web3.eth.defaultAccount, callback);
}
1

Callback basically is a function which is passed to other function and executed there when you call this "callback". Very simple example can be found on mozilla docs.
If you don't pass any callback, depending on function code it may or may not affect your program, since callback will be null.

1

Some web3 methods are asynchronous and require a callback.

The callback function is executed once the original function is done and takes a transaction hash or similar as an argument.

You can avoid callbacks entirely by using an async/await pattern.

For instance:

async function signPayment(recipient, amount, nonce, contractAddress) {
  var hash = "0x" + ethereumjs.ABI.soliditySHA3(
    ["address", "uint256", "uint256", "address"],
    [recipient, amount, nonce, contractAddress]
  ).toString("hex");

  var signed = await web3.personal.sign(hash, web3.eth.defaultAccount);
  console.log(signed);
}
  • @async @Maxpeinas Thank you. Is there any advantages for each of approaches : callback vs. async ? Thanks – Questioner Jun 28 '18 at 11:28
  • 1
    @sas Check out this gist: gist.github.com/Kaisle/bece5cbdcac17385d2f8e0cfa7c6b095. Just replace the arguments with the arguments from your code (and ignore the callback argument, you don't need it) – Soggiorno Jul 3 '18 at 13:49
  • 1
    Have you included the dependency in your file using require('ethereumjs-abi') or similar? – Soggiorno Jul 3 '18 at 14:30
  • 1
    try the following: var ethereumjs = require('ethereumjs-abi'); – Soggiorno Jul 3 '18 at 14:46
  • 1
    try without ABI: ethereumjs.solidityShA3 – Soggiorno Jul 3 '18 at 15:16

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.