I have the following code
const broadcastTxn = await web3.eth
.sendSignedTransaction(txn.signed)
.on('receipt', (r) => console.log('Receipt', r))
.on('confirmation', (c) => this.handleConfirmation(c, txn));
...
handleConfirmation(c: number, txn: Transaction): void {
// do some stuff
}
I get multiple confirmations
returned, but after the 3rd I'd like to cancel the callback/event that continues listening for .on('confirmation')
I tried putting logic in the handleConfirmation
function to throw
handleConfirmation(c: number, txn: Transaction): void {
// do some stuff
if (c >= 3) throw new Error('cancelling callback');
}
but that doesn't work, it keeps getting called.
What is the correct way to end the .on('confirmation')
listener?
es2017 & Node 14.9.0
@ThomasSablik pointed me in the correct direction. I needed to capture the object without using await
. Then I could reference it and use await
afterwards. Solution below
const signedTxnListener = web3.eth
.sendSignedTransaction(txn.signed)
.on('receipt', (r) => console.log('Receipt', r))
.on('confirmation', (c) => this.handleConfirmation(c, txn));
await signedTxnListener
...
handleConfirmation(c: number, txn: Transaction): void {
// do some stuff
if (c >= 3) signedTxnListener.off('confirmation');
}