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 = "ed7fd12135d541c6bc03149c3532ef11"
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()呼叫的注意事項,網上大多數文章也都是復制粘貼官網的示例,簡直傻逼!
希望這篇文章可以幫助到有這方面需求的小伙伴,如果有問題和想法評論下留言交流即可,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/356805.html
標籤:區塊鏈
上一篇:第十次股票交易日志
