Web3js
非同步發送多個 tx 後退出程序
我編寫了一個函式,允許我向我的智能合約非同步發送任意數量的交易。但是,即使在最後一個事務完成後,該過程仍保持打開狀態。目前,我必須手動按 CTRL+C 退出。我希望我的程序在最後一個事務完成後自動退出。我該怎麼做呢?
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) }) } }
你可以使用
Promise.all
和使用process.exit(0)
來處理這個問題。它應該按您的意願工作:
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); }); }