[英]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')
我收到多个
confirmations
返回,但在第三次之后我想取消继续侦听.on('confirmation')
的回调/事件
I tried putting logic in the handleConfirmation
function to throw我尝试将逻辑放入
handleConfirmation
function 以抛出
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?结束
.on('confirmation')
侦听器的正确方法是什么?
es2017 & Node 14.9.0
@ThomasSablik pointed me in the correct direction. @ThomasSablik 为我指出了正确的方向。 I needed to capture the object without using
await
.我需要在不使用
await
的情况下捕获 object 。 Then I could reference it and use await
afterwards.然后我可以参考它并在之后使用
await
。 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');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.