如何尽快获取异步函数中的值?

问题描述

我正在使用以太坊区块链,但是我的问题是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.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);

并在您的App类中:

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)
    })
}