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

Tags: , , , ,



I’m working with Ethereum blockchain, but my problem my is JavaScript (async, await function).

Here my code simplified:

In my 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 );
});  
    

In my App.js file

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

Any help with any code of example?
Thanks a lot in advance.

Answer

Welcome to the fantastic world of asynchronism… One way to do this would be :

const hash_returned = await App.addBlockChain(n.username, n.first, n.last, n.email);

and in your App class :

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


Source: stackoverflow