I want to end the process after sendTransaction return transactionHash. Here is my code currently :
const Web3 = require('web3');
const web3 = new Web3("http://127.0.0.1:8545");
async function task(db) {
const accounts = await web3.eth.getAccounts();
const length = accounts.length;
// Do multiple transaction
while (length--) {
feeTx = {
...
}
await web3.eth.sendTransaction(feeTx, async function (err, transactionHash) {
if (err) {
// await for db(mongo) insert then continue loop
await db.insert(err);
} else {
console.log("DONE");
// await for db(mongo) insert then continue loop
await db.insert(transactionHash);
}
});
}
}
// do db connection first
db = ....
await task(db);
// Close db connection
db.close();
// The process should be ended here.
// but it doesn't end, if one of the transaction is still pending to be mined,
// even I already get all the transactionHash from task()
// The process will be ended when all the transaction is success(mined).
This process won't be ended if one of the transaction is still pending even I already get all the transactionHash. I know can end the process by process.exit(0)
manually, but I believe that this is risk for my code(Since it is an async loop). So is there any method and more safety way to end the process after I get all the transactionHash?
Sinice code above is a little bit complicated, this one would be clearly:
const Web3 = require('web3');
const web3 = new Web3("http://127.0.0.1:8545");
async function task(db) {
const accounts = await web3.eth.getAccounts();
const length = accounts.length;
try {
// Do multiple transaction
while (length--) {
feeTx = {
...
}
// What i want is only the transactionHash(It will return me immediately without the transaction be mined).
// sendTransaction here will wait until it get the receipt (The transaction is already be mined).
const transactionHash = await web3.eth.sendTransaction(feeTx);
// transactionHash logging
await db.insert(transactionHash);
}
} catch (err) {
// Error logging
await db.insert(err);
}
}
// do db connection first
db = ....
await task(db);
// Close db connection
db.close();
// The process will end here. With long processing since it wait until all the transaction be mined
web3
instance is connected via WebSocket (ws
at the beginning of your provider URL), then you need to close it explicitly.length < 0
then the process is gonna take a very long time to complete.await
only inside anasync
function. So I know for a fact that you haven't even tried it (at least not the version you've just posted).on
are "async" (return before completion), which would actually make your loop end faster rather than running forever. Add printouts in your code, gather some more information and come back with that. Please.