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()调用的注意事项,网上大多数文章也都是复制粘贴官网的示例,简直傻逼!
希望这篇文章可以帮助到有这方面需求的小伙伴,如果有问题和想法评论下留言交流即可。