Web3 Callback – Input Parameter for Callback Function in Web3.js

javascriptweb3js

I want to send the parameter to the function in smart contract i tried different ways but it keeps giving me error.

My solidity file is

 pragma solidity ^0.4.18;

 import "./ConvertLib.sol";

 contract Check {
 function multiply(uint a) public pure returns(uint){
    return a*a;
 }
}

I connected to Web3 sucessfully and created the instance of contract as inst. When i try to execute the function

 console.log(inst.multiply.call()(function(err,result){console.log("r-->"+result);}));

it gives me error

Invalid number of arguments to Solidity function

and if i add argument like this

console.log(inst.multiply(2).call()(function(err,result){console.log("r-->"+result);}));

or like this

console.log(inst.multiply.call(2)(function(err,result){console.log("r-->"+result);}));

it gives me this error

Error: The MetaMask Web3 object does not support synchronous methods like eth_call without a callback parameter.

I am using Web3 version 0.20.3

Best Answer

As per the web3 docs:

myContract.methods.myMethod([param1[, param2[, ...]]]).call(options[, callback])

Truffle and Ganache

inst.methods.multiply(2).call()
    .then(function(result) {
        console.log("r-->"+result);
    })
    .catch(function(err) {
        console.log("err-->"+err);
    }
);

Or, simpler:

inst.methods.multiply(2).call().then(console.log).catch(console.log);

Metamask

inst.multiply(2, function(err, result) {
    console.log("r-->"+result);
})