web3.js查询方法的调用方式汇总

web3.js中的constant方法调用:

(1)调用方式1

contractAddr.register.call(amount, {from: account});

constant方法不需要gas。【from参数可以省略】

(2)调用方式2

contractAddr.register.call(amount, {from: account}).then(function(returnValue) {

  console.log(returnValue.valueOf());

});

可以获得constant函数真正的返回值。【from参数可以省略】

(3)调用方式3 

 contractAddr.register(amount, {from:account}).then(function(returnValue) {

    console.log(returnValue.valueOf());

  });

也可以不使用call(),直接调用比较方便,也为了和交易tx方法统一。【from参数可以省略】


web3.js对于constant方法返回值的测试

  • 一个返回值测试

可以返回uint,int,bytes32,address,string,bool;

int数组、uint数组、address数组、bytes32数组(如何将返回的bytes32转化为字符串输出请参考下面)

但是不能返回string数组(用返回bytes32代替).

  • 多个返回值测试

可以返回多个值,其实相当于返回一个数组,这多个返回值中可以包含数组。参考代码如下:

合约中的实现:

function register(int ui)constant returns(bool, int, string, bytes32, address) {



    if(ui != 0) {

        return (true, ui, "success", "bytes32", 0x39ff90056661184448e18b2517d018660babcb48);

    }

    else {

        return (false, ui, "fail", "bytes323232", 0x39ff90056661184448e18b2517d018660babcb49);

    }

}

js中的实现:

  contractAddr.register(amount, {from: account}).then(function(returnValue) {



      console.log(returnValue[0]);

      console.log(returnValue[1].valueOf());

      console.log(returnValue[2]);

      console.log(hexCharCodeToStr(returnValue[3]));

      console.log(returnValue[4]);



  });

猜你喜欢

转载自blog.csdn.net/CHENYUFENG1991/article/details/81265448