1

I have written a function that allows me to send an arbitrary amount of transactions, asynchronously, to my smart contract. However the process stays open even after the last transaction has finished. Currently, I have to manually press CTRL+C to exit. I would like for my program to automatically exit once the last transaction has finished. How would I go about doing this?

async function multipleTx(n) {
  accounts = await web3.eth.getAccounts()
  let totalGasUsed = 0
  for (let i = 0; i < n; i++) {
    instance.methods
      .addSubmission(i, i, i, i)
      .send({
        from: accounts[0],
        gasPrice: 10000000000,
      })
      .then((receipt) => {
        console.log(receipt)
        totalGasUsed += receipt.gasUsed
        console.log(totalGasUsed)
      })
  }
}

1 Answer 1

1

You can use Promise.all and the use process.exit(0) to deal with this problem.

It should work as you want:

async function multipleTx(n) {
  accounts = await web3.eth.getAccounts();
  let totalGasUsed = 0;

  const promisesArr = []; // make empty array
  for (let i = 0; i < n; i++) {
    promisesArr.push( // add promises to array
      instance.methods.addSubmission(i, i, i, i).send({
        from: accounts[0],
        gasPrice: 10000000000,
      })
    );
  }

  // Execute all promises and then exit process
  Promise.all(promisesArr).then((receipts) => {
    receipts.forEach((receipt) => {
      totalGasUsed += receipt.gasUsed;
    });

    console.log('Total gas used:', totalGasUsed);
    process.exit(0);
  });
}
1
  • 1
    Thank you this worked exactly the way i wanted! I found out about the Promise.all() but i failed to realize that i was getting and array of receipts and so i didn't use the forEach loop and it got weird haha, Thanks!
    – Conviley
    Commented Apr 15, 2020 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.