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 >= new Date().getTime()) {
       }
    }
    let web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/XXXXX"));
    var balance;
    web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1").then(bal => balance = bal);
    sleep(5000);
    document.write(balance + "<BR>");

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

  • "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 2 at 7:59
1

You can use the async/await pattern :

const balance = await web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); 
| improve this answer | |
  • 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 – Hentai Ousama Sep 2 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.