当前位置: 代码迷 >> JavaScript >> 使用async / await承诺NodeJS获取事务哈希
  详细解决方案

使用async / await承诺NodeJS获取事务哈希

热度:117   发布时间:2023-06-13 12:26:17.0

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

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上看到它们。 问题是关于Promises的JavaScript us。

在这种情况下,控制台注销:

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

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

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

  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. 基于事件发射器:

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