简体   繁体   中英

Input Parameter for callback function Web3

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

I've been having the same problem with the Hello World contract and after pulling my hairs for a while I tried something like:

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

That is, passing a callback function as the last parameter. As it says in the documentation, "all its functions [Solidity's] use synchronous HTTP requests by default. If you want to make an asynchronous request, you can pass an optional callback as the last parameter to most functions. All callbacks are using an error first callback style:"

web3.eth.getBlock(48, function(error, result){
   if(!error)
       console.log(JSON.stringify(result));
   else
       console.error(error);
})

Try something like this:

inst.methods[multiply](2).call().then(data => ...).catch(err => {...})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM