Javascript 如何尽快在异步函数中获取值?
我正在使用以太坊区块链,但我的问题是JavaScript(异步,等待函数) 下面是我的简化代码: 在我的html中Javascript 如何尽快在异步函数中获取值?,javascript,promise,async-await,transactions,ethereum,Javascript,Promise,Async Await,Transactions,Ethereum,我正在使用以太坊区块链,但我的问题是JavaScript(异步,等待函数) 下面是我的简化代码: 在我的html中 App.addBlockChain(n.username,n.first,n.last,n.email).then(value => { **//here I need the hash of my transaction** }).catch(error => { alert("Errore: " + error ); });
App.addBlockChain(n.username,n.first,n.last,n.email).then(value => {
**//here I need the hash of my transaction**
}).catch(error => {
alert("Errore: " + error );
});
在我的App.js文件中
addBlockChain: async(u,n,c,e) => {
let hash;
const web3 = new Web3(App.web3Provider);
const signed = await web3.eth.accounts.signTransaction(options, account.privateKey);
const receipt = await web3.eth.sendSignedTransaction(signed.rawTransaction)
.on('transactionHash', function(hash_returned){
//I need this hash hash_returned as soon as possible in my html ***
hash= hash_returned;
})
.on('receipt', function(receipt){... })
.on('confirmation', function(confirmationNumber, receipt){ ... })
.on('error', console.error); // If a out of gas error, the second parameter is the receipt.;
return hash; //it is returned only when on('confirmation') is terminated
有关于示例代码的帮助吗?非常感谢。欢迎来到异步的奇妙世界。。。一种方法是:
const hash_returned = await App.addBlockChain(n.username, n.first, n.last, n.email);
在应用程序类中:
addBlockChain: async(u, n, c, e) => {
const web3 = new Web3(App.web3Provider);
const signed = await web3.eth.accounts.signTransaction(options, account.privateKey);
return new Promise(resolve => { // addBlockChain must return a Promise, so it can be "await"ed
web3.eth.sendSignedTransaction(signed.rawTransaction)
.on('transactionHash', function(hash_returned) {
resolve(hash_returned); // now that you have hash_returned, you can return it by resolving the Promise with it
})
// or more simply (equivalent) :
// .on('transactionHash', resolve)
})
}
是什么让您认为存在某种延迟,或者等待或延迟哈希_返回的内容?将('transactionHash',函数(哈希_返回)放入返回不会返回任何东西,但您说您希望尽快返回。您从未提及任何东西都没有返回。这是另一个问题。@JeremyThille好的,我修改了我的问题。这回答了您的问题吗?您救了我的命。我永远不会找到这些解决方案(解决我不知道的问题)但我保证会深化话题。非常感谢,如果你路过意大利,我欠你一杯咖啡哈,我刚从费伦泽回来:)不过无论如何,谢谢!