node.js - Web3 BatchRequest 总是返回未定义,我做错了什么?
问题描述
我试图使用 web3 Batch 来调用代币余额。当我调用 batch.execute() 时,它返回未定义而不是已添加到批处理中的已解决请求。有人可以告诉我我在哪里搞砸了?这是我的代码。
async generateContractFunctionList(
address: Address,
tokens: Token[],
blockNumber: number
) {
const batch = new this.web3.BatchRequest();
for (let i = 0; i < tokens.length; i++) {
const contract = new this.web3.eth.Contract(balanceABI as AbiItem[]);
contract.options.address = tokens[i].address;
batch.add(
contract.methods
.balanceOf(address.address)
.call.request({}, blockNumber)
);
}
return batch;
}
async updateBalances() {
try {
const addresses = await this.addressService.find();
const tokens = await this.tokenService.find();
const blockNumber = await this.web3.eth.getBlockNumber();
for (let i = 0; i < addresses.length; i++) {
const address = addresses[i];
const batch = this.generateContractFunctionList(address, tokens, blockNumber);
const response = await (await batch).execute();
console.log(response); //returns undefined
}
} catch (error: unknown) {
if (error instanceof Error) {
console.log(`UpdateBalanceService updateBalances`, error.message);
}
}
}
为什么 batch.execute() 不返回任何东西并且是无效的?我参考了这篇文章中的这个例子,并根据我的需要对其进行了修改,但并没有改变太多可能会搞砸的东西。
https://chainstack.com/the-ultimate-guide-to-getting-multiple-token-balances-on-ethereum/
当我向“batch.add”和控制台日志添加回调函数时,余额被记录到控制台。但是我正在尝试在 .execute() 上使用异步等待,所以我怎样才能从使用 await batch.execute() 的方法调用中获得结果,并将所有回调结果都保存在其中,就像它在博客文章中所写的那样。
解决方案
面临同样的问题。一个快速而肮脏的解决方案是使用包的过时版本。
包.json:
....
"dependencies": {
...
"web3": "^2.0.0-alpha.1",
...
}
....
推荐阅读
- c - 如何判断 C 输入是否为 8 位二进制数
- macos - 如何从自制的 tcl-tk 包中获取 tls?
- javascript - window.location 在新选项卡中打开链接
- python-3.x - 无法使用颜色图并在没有位移的情况下保存图像
- python - SMTP Python 连接意外关闭
- python - 从python中的类外部访问一个类中的多个列表(或其他变量)
- c# - NUnit 测试方法 Event raise 抛出错误
- python - 添加,减去 datetime.time 列 pandas
- google-apps-script - 如何使用 Google Apps 脚本检索用户为 Google 表单中的其他字段输入的值?
- php - Nginx 502 坏网关 + PHP 7.2 FPM