web3 批量请求 BatchRequest batch.execute()

web3.js BatchRequest batch.execute() 批量请求示例

这个是官方示例,用的时候一直有问题,不能正常调用。
原因是,我的方法原来使用的是异步函数,但是batch.execute(),只能同步调用。

Talk is cheap ,show my code


const abi = [{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}];
const address = "0xe39F7C4414bd30A992E971b5242c265dd5B9e67F"
var Web3 = require('web3');
var infuraKey = ""
var web3 = new Web3("https://rinkeby.infura.io/v3/"+infuraKey);

async function main(){
    var accountAddress = "0xD993d1049bd38eDBe12f8F6c9cdB716970B778D2";
    var batch = new web3.BatchRequest();
    var contract = new web3.eth.Contract(abi, address);
    
    
    console.log(await web3.eth.getBalance(accountAddress))
    console.log(await web3.eth.getGasPrice())
    console.log(await contract.methods.balanceOf(accountAddress).call());

    // EVM的系统数据,参数放在request的方法里,带参数的要加一个区块号
    batch.add(web3.eth.getBalance.request(accountAddress,'latest',(err,result)=>{console.log("b1 ----"+result)}));
    // EVM的系统数据,参数放在request的方法里,不带参数的,只有回调函数
    batch.add(web3.eth.getGasPrice.request((err,result)=>{console.log("b2 ----"+result)}));
    // 自定义合约方法,写法与单个没太大区别,只是把call()方法的小括号去掉,直接 '.'+ request 方法
    batch.add(contract.methods.balanceOf(accountAddress).call.request({},(err,result)=>{console.log("b3 ----"+result)}));

    batch.execute()

}

// 同步调用,可以正常输出
main()

// 原来使用的是这样的写法,不能用
// main()
//   .then(() => process.exit(0))
//   .catch(error => {
//     console.error(error);
//     process.exit(1);
//   });

简单说明下:

同步调用的情况,可以正常输出:

在这里插入图片描述
异步调用,batch.execute()不能输出:
在这里插入图片描述

吐槽一下,官方的示例中并没有描述batch.execute()调用的注意事项,网上大多数文章也都是复制粘贴官网的示例,简直傻逼!

希望这篇文章可以帮助到有这方面需求的小伙伴,如果有问题和想法评论下留言交流即可。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值