首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sendsignedtransaction中的回调函数与on函数

sendsignedtransaction中的回调函数与on函数
EN

Ethereum用户
提问于 2020-01-21 06:16:35
回答 1查看 772关注 0票数 1

我正在使用web3js部署一个智能契约,它工作得非常完美。但我意识到我对回调的错误使用。我从https://web3js.readthedocs.io/en/v1.2.1/callbacks-promises-events.html获得了对promievents的一些基本理解,并根据下面的示例重写了代码:https://web3js.readthedocs.io/en/v1.2.0/web3-eth.html#sendsignedtransaction

代码语言:javascript
复制
web3.eth.getTransactionCount(account, (err, txCount) => {
    if (err!=null) {console.log('error executing web3.eth.getTransactionCount: ', err)}
    else{
        console.log('txCount: ',txCount)

        const txObject = {
            nonce: web3.utils.toHex(txCount),
            gasLimit: web3.utils.toHex(1000000),
            gasPrice: web3.utils.toHex(web3.utils.toWei('0', 'gWei')),
            data: contractByteCode
        }

        const tx = new EthereumTx(txObject,{common: customCommon})

        tx.sign(privateKey)

        const serializedTransaction = tx.serialize()
        const raw = '0x' + serializedTransaction.toString('hex')

        web3.eth.sendSignedTransaction(raw)
        .on('transactionHash',(hash) => {
            console.log('txHash:', hash)
        })
        .on('receipt',(receipt) => {
            console.log('receipt', receipt)
        })
        .on('error', console.error)
    }

})

我这样做是基于一个原则,即getTransactionCount()中的回调可以在将来的任何时候执行,所以我应该只在回调中使用返回值txCount。这就是为什么整个代码都在回调函数中。

但我不确定发送交易部分。我假设".on(' transactionHash ')“函数将在sendsignedtransaction函数发出transactionHash事件时执行。类似地,“.on(‘接收’)”函数将在sendsignedtransaction函数发出接收事件时执行。每当sendsignedtransaction函数发出错误事件时,".on(' error ')“函数就会执行。所以所有东西都异步工作,而不阻塞我的线程。

如果我的理解是正确的,那么当我故意放进一个bug时,为什么这段代码只挂在节点中(通过删除“{ put : customCommon}”参数)。它不应该立即返回并执行"console.error“吗?

EN

回答 1

Ethereum用户

发布于 2020-01-21 06:48:29

以下是一般计划:

  • 事务发送后立即触发transactionHash (几乎立即)
  • 当事务收据可用时触发receipt
  • 如果在此过程中的任何点发生错误,则会触发error
  • 在第12次确认之前,每次确认都会触发confirmation

请注意,等待的确认次数越多,事务永远保持在块链中的概率就越高。

有关更多细节,请参见正式文件 (web3.jsv1.2.0)。

票数 2
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/79148

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档