繁体   English   中英

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

[英]How to get a value in async function as soon as possible?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM