Node.js for()循环值是否不断增加?

时间:2019-10-31 11:32:30

标签: javascript node.js asynchronous web3 web3js

我为批处理订单设置了间隔和循环,

但是for循环中的批号一直在增加。

这是我的代码

const Web3 = require('web3')
const web3 = new Web3('ws://127.0.0.1:8546')

const accounts = require('./tps.json');

const quoteInterval = 5 * 1000;

const batch = new web3.BatchRequest();

const sendTransactions = async () => {
  try {
    for (let i = 0; i < 100; i++) {
      let account = accounts[i];
      const tx = web3.eth.sendTransaction.request(
        {
          from: web3.utils.toChecksumAddress("0xa00ce1f7fbf8298f4163ab23de8752942bdff98e"),
          to: web3.utils.toChecksumAddress(account),
          gas: 21000,
          gasPrice: 1000000000,
          value: 1
        }
      )
      batch.add(tx)
    }
    await batch.execute().then(console.log);
  } catch (error) {
    console.log(error);
    process.exit(1)
  }
};

if (web3.eth.net.isListening()) {
  sendTransactions();

  setInterval(() => {
    sendTransactions();
  }, quoteInterval);
}

i值没有增加,但是sendTransactions()函数在每个时间间隔后的运行次数分别为2、3、4或5次

2 个答案:

答案 0 :(得分:0)

您在哪里看到i的值不断增加?您是否在某处放了console.log

以下简化版本(具有与您相同的上下文操作)可以正常工作:

async function asyncOperation(x) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log(x) # this always outputs 0 < x < 5
            resolve()
        }, 50)
    })
}

const asyncFunction = async () => {
    allPromises = []
    for (let i = 0; i < 5; i++) {
        allPromises.push(asyncOperation(i))
    }
    await Promise.all(allPromises)
};

setInterval(() => asyncFunction(), 500)

答案 1 :(得分:0)

const quoteInterval = 5*1000;

const sendTransactions = async () => {
  try {
    for (let i = 0; i < 100; i++) {
    console.log(i);
    
    }
    
  } catch (error) {
    console.log(error);
    
  }
};


  sendTransactions();

  setInterval(() => {
    sendTransactions();
  }, quoteInterval);

按照逻辑,它不会超过100