【问题标题】:Sending .send requests in loop only sets the last value of the loop i amount of times在循环中发送 .send 请求只会设置循环的最后一个值 i 次
【发布时间】:2018-05-17 09:38:02
【问题描述】:
    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”

【问题讨论】:

  • 这实际上是您正在运行的代码吗?您的帖子标题提到了i,这听起来像是您在使用for 循环,其中循环变量范围可能会导致您所描述的挑战。
  • 我完全明白你的意思,很抱歉造成混乱。我曾经运行一个 for 循环,现在不再运行,实际上我找到了一个解决问题的解决方案,现在我将其作为答案发布。

标签: ethereum web3 web3js metamask


【解决方案1】:

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

实际上只发送last 事务的原因是,nonce 可以用作在事务之前覆盖事务的一种方式被开采(就像你用太少的气体发送它)。

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

Repeating transactions hangs - web3js, local geth

【讨论】:

  • 谢谢,我会调查一下
  • 尽管这看起来是解决我的问题的合乎逻辑的方式,但我无法让您的解决方案在我的上下文中发挥作用。
【解决方案2】:

我为这个问题找到了一个 hacky 解决方案,并在 web3 github 上创建了一个问题。

在这里查看我的问题和我的解决方案:https://github.com/ethereum/web3.js/issues/1636

我找不到一个简洁的解决方案,但我确信一旦发现问题,就会提出解决方案。

【讨论】:

    猜你喜欢
    • 2011-07-01
    • 2012-09-03
    • 2019-08-01
    • 1970-01-01
    • 2013-11-18
    • 2013-10-24
    • 2020-01-01
    • 2021-06-22
    • 2022-01-23
    相关资源
    最近更新 更多