首页 > 解决方案 > 在循环中发送 .send 请求只会设置循环的最后一个值 i 次

问题描述

    let batch = new this.web3.BatchRequest();

    const arr = [
        {name: "test1", att: 100, def: 100},
        {name: "test2", att: 100, def: 100},
        {name: "test3", att: 100, def: 100},
        {name: "test4", att: 100, def: 100},
    ]
    arr.forEach((d) => {
        batch.add(this.contract.methods.createCountry(d.name, d.att, d.def, 10, this.account).send.request(this.contractObject, (err, res) => {
            if (err) {
                throw err;
            } else {
                console.log(res);
            }
        }));
    });
    console.log(batch);
    batch.execute();

我知道问题不是智能合约,因为我在 Remix 中对它进行了彻底的测试,并在不同的国家/地区进行了推送。我使用 web3 和 Metamask。

合约中的所有值都设置为“test4”

标签: ethereumweb3web3jsmetamask

解决方案


当背靠背发送许多事务时,您必须为每个事务设置随机数,并增加它。通常,nonce 是由节点为您设置的,但它不适用于多个顺序事务。

仅实际发送最后一笔交易的原因是, nonce可以用作在交易被挖掘之前覆盖交易的一种方式(例如,如果您发送的 gas 太少)。

我之前已经用代码示例回答了这个问题

重复事务挂起 - web3js,本地 geth


推荐阅读