0

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.

alfo888_ibg
  • 1,847
  • 5
  • 25
  • 43

1 Answers1

1

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)
    })
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
  • You saved my days. I would never have come to these solutions (resolve i didnt' know) but I promise to deepen the subject. Thank you very much, if you pass by Italy I owe you for a coffee – alfo888_ibg Sep 18 '20 at 09:57
  • 1
    Ha, I just came back from Firenze :) But thanks anyways! – Jeremy Thille Sep 18 '20 at 11:07