1

Here is a very simple code that i am using :-

    let web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/XXXXX"));
    var balance;
    web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(bal => balance = bal);
    document.write(balance + "<BR>");

And it gives me the output undefined. So i decided to wait for 5 seconds before printing the output.

    function sleep(miliseconds) {
       var currentTime = new Date().getTime();
   while (currentTime + miliseconds &gt;= new Date().getTime()) {
   }
}
let web3 = new Web3(new Web3.providers.HttpProvider(&quot;https://ropsten.infura.io/v3/XXXXX&quot;));
var balance;
web3.eth.getBalance(&quot;0x407d73d8a49eeb85d32cf465507dd71d507100c1&quot;).then(bal =&gt; balance = bal);
sleep(5000);
document.write(balance + &quot;&lt;BR&gt;&quot;);

This waits for 5 seconds and the output is still undefined. What is the proper way to store the result of promise in an external variable?

I don't want to print the result inside the .then(bal => document.write(bal));

Hokkyokusei
  • 285
  • 1
  • 2
  • 8
  • "I don't want to print the result inside the .then(bal => document.write(bal));" - but that's your one and only option. This result is retrieved from another process, therefore, asynchronously of your process. – goodvibration Sep 02 '20 at 07:59

1 Answers1

1

You can use the async/await pattern :

const balance = await web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); 
clement
  • 4,302
  • 2
  • 17
  • 35
  • So i have written this :- async function ffuu() { document.write("Something"); const bl = await web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); document.write(bl + "<BR>"); }

    but the output is just something and then nothing prints

    – Hokkyokusei Sep 02 '20 at 21:02