简体   繁体   中英

Cancel .on event listener/callback

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM