使用异步/等待nodejs获得交易哈希



我想通过运行此代码来获取事务哈希:

const transactionId = await web3.eth.sendSignedTransaction('0x' + serializedTransaction.toString('hex') ).on('receipt', function(receipt) {
    return receipt.transactionHash;
});
// Now it is known the transaction ID, so let's build the public Etherscan url where the transaction details can be viewed.
const url = `https://rinkeby.etherscan.io/tx/${transactionId}`
console.log(url)

代码对交易的关注,我可以在etherscan上看到它们。问题是关于诺言的JavaScript我们。

i这种情况下的控制台记录:

https://rinkeby.etherscan.io/tx/[object Object]

我尝试了不同的方法来获得交易哈希,但没有成功。你能帮助我吗?这也可能是更好地了解承诺如何工作的正确机会。

您将承诺与事件发射器(可能是可能的)结合在一起,但是我建议在基于事件 - 符号的方法之后尝试首先基于承诺的方法。之后,您可以尝试混合物。:)

  1. 承诺基于:

    async function fetch(){ const transactionID = await web3.eth.sendSignedTransaction('0x'+serializedTransaction.toString('hex'));return transactionID; }let a = fetch() a.then(response=>console.log('transactionHash => ' + response)   .catch(error => console.log('error with sending transaction => ' + error);
    
  2. 基于事件 - emmiter:

    const transactionID = web3.eth.sendSignedTransaction('0x'+
    serializedTransaction.toString('hex'))
    .on('transactionHash',console.log) 
    .on('receipt', console.log);
    

最新更新