1.创建web3实例,setting provider:
if(typeof web3!=='undefined'){
web3= new Web3(web3.currentProvider);
} else{
web3=new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
然后就可以使用web3对象的API了。
2.使用回调callbacks:
web3对象的API默认是使用http同步请求的,如果需要使用异步请求,可以使用以下的例程:error first callback
web3.eth.getBlock(48,function(error,result){
if(!error)
console.log(JSON.stringify(result));
else
console.error(error);
}
定义错误优先回调有以下两个规则:
(1)回调的第一个参数是为第一个错误对象保留的,如果发生错误将由第一个error参数返回。
(2)回调的第二个参数保留给任何响应成功的数据。如果没有错误发生,error将被设置为空,并且任何成功的数据将在第二个参数中返回。
一个简单的例子包含多个回调 :
// Example taken from caolan/async README
async.parallel({
one: function(callback){
setTimeout(function(){
callback(null, 1);
}, 200);
},
two: function(callback){
setTimeout(function(){
callback(null, 2);
}, 100);
}
},
function(err, results) {
// results is equal to: {one: 1, two: 2}
})
当然又发现了promise用法,promise相比之下具有更多优势:
promise
4.web3j api 汇总
扫描二维码关注公众号,回复:
3812541 查看本文章