1

Here is contract:

pragma solidity ^0.4.17;

contract Demo{

  string public data;

  function Demo()public{
    data = "Jiu Wei";
  }

  function getData() public view returns (string) {
      return data;
  }
}

Here is web3.js code:

var abi = /*abi*/

var address = "0x850e97f8692ffe27c867b1401244691736c021ee";

var myContractInstance = web3.eth.contract(abi).at(address);

myContractInstance.getData.call(function (result, error) {
  if(!error) {
      console.log(result);
  }
});

The question is it returns null all the time.

What should I do for the code?

Please give me some advice on how to handle a situation like this. Thank you in advance.

1

The issue is actually quite straightforward: you mixed up the order of the (result, error) parameters in the callback function passed to call(). Since the call actually returns the right data, there is a result and nothing gets printed.

So the right approach is the following (error first, result after):

myContractInstance.getData.call(function (error, result) {
  if(!error) {
    console.log(result);
  }
});

I would strongly advise however that you catch the error and handle it safely. Furthermore there are 3 things you could improve regarding the stack used here:

  • Switch to the latest version of web3.js (1.0.x instead of 0.2.x)
  • Switch to a more recent version of the Solidity compiler (0.4.25 instead of 0.4.17)
  • Switch to new JavaScript syntax, leveraging elements such as const to ensure to flag securely variables that should not be mutable (your contract address for example).

These elements will help you improve both the readability and security of your code. Hope it helps.

  • you are right, I will do like you said. Thanks a lot. – februarysea Oct 29 '18 at 11:58

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.