web3.eth.contracts.方法await函数永远不会返回



我正在做一个与以太坊智能合约交互的项目。一切正常,交易正常,等等……但我意识到,当我试图在一个特定的await函数之后运行一些代码时,这些代码永远不会运行,我真的不知道为什么。我调用的其他契约方法工作正常,代码执行正常。

代码:

onSubmit = async (event) => {
event.preventDefault()
console.log("Submitting the form...")
var day = new Date(Date.now()).getDate()
var month = new Date(Date.now()).getMonth() + 1
var year = new Date(Date.now()).getFullYear()
var today = new Date(year, month -1, 1)
var todayTime = today.getTime()
const ipfsadded = await ipfs.add({path:this.state.fileName, content:this.state.buffer})
var ipfsHash = ipfsadded.cid.toString()
this.setState({ipfsHash: ipfsHash})
console.log('hash:', ipfsHash, " / name =", this.state.fileName )
console.log("inserindo na blockchain..")
const accounts = await web3.eth.getAccounts()
//ERROR HERE!!
//THIS FUNCTION IS EXECUTED, THE TRANSACTION IS CONFIRMED IN METAMASK BUT AFTER THAT NOTHING HAPPENS
var result = await contract.methods.add(ipfsHash, this.state.fileName, this.state.fileType, todayTime).send({from:accounts[0], gas:300000});
console.log("resultado =", result) //IS NEVER EXECUTED EVEN WITH TRANSACTION OK
console.log("File submitted on blockchain!") //IS NEVER EXECUTED

}

这可能是因为交易没有在750秒内被挖掘,.send抛出了一个错误,但没有被捕获。你可以通过用try/catch块包装它并检查错误来证明。

try {
var result = await contract.methods.add(ipfsHash, this.state.fileName, this.state.fileType, todayTime).send({from:accounts[0], gas:300000});
} catch(err) {
console.error(err);
}

较好的方法是订阅receipt,transactionHashconfirmation事件,这些事件由send公开。

contract.methods.add(ipfsHash, this.state.fileName, this.state.fileType, todayTime)
.send({from:accounts[0], gas:300000})
.on('transactionHash', resolve)
.on('error', reject);

在你的例子中应该是

onSubmit = async (event) => {
event.preventDefault()
console.log("Submitting the form...")
var day = new Date(Date.now()).getDate()
var month = new Date(Date.now()).getMonth() + 1
var year = new Date(Date.now()).getFullYear()
var today = new Date(year, month -1, 1)
var todayTime = today.getTime()
const ipfsadded = await ipfs.add({path:this.state.fileName, content:this.state.buffer})
var ipfsHash = ipfsadded.cid.toString()
this.setState({ipfsHash: ipfsHash})
console.log('hash:', ipfsHash, " / name =", this.state.fileName )
console.log("inserindo na blockchain..")
const accounts = await web3.eth.getAccounts()
//ERROR HERE!!
//THIS FUNCTION IS EXECUTED, THE TRANSACTION IS CONFIRMED IN METAMASK BUT AFTER THAT NOTHING HAPPENS
const promise = new Promise()
contract.methods.add(ipfsHash, this.state.fileName, this.state.fileType, todayTime)
.send({from:accounts[0], gas:300000})
.on('receipt', (receipt) => {
console.log('this should be executed now')
console.log("resultado =", receipt)
console.log("File submitted on blockchain!")
})
.on('error', console.error)
}

以下任何一个答案https://ethereum.stackexchange.com/a/58936/6814和https://ethereum.stackexchange.com/a/59114/6814都是正确的。

相关内容

  • 没有找到相关文章

最新更新