Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate Value from JS Promise

I have assigned a callback function to a variable. The function then returns a promise stating it is fulfilled and the value. I want to be able to return the value and use it to perform a mathematical calculation.

Javascript code:

const DollarValue = web3.eth.getBalance(address, (err, balance) =>{
    const EthValue =  web3.utils.fromWei(balance, 'ether')
    TotalEth = parseFloat(EthValue) * 4000;
    return TotalEth;
  
})

console.log(DollarValue);

In the console I get the below output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Promise { <state>: "pending" }
​
<state>: "fulfilled"
​
<value>: "338334846022531269"

>Solution :

Assuming this is the interface you’re using, this is an asynchronous interface and thus you cannot directly return the value from the function or its callback as the function will return long before the value is available. You have two choices. Either use the balance or TotalEth value that you calculate from it inside the callback or skip the callback entirely and use the promise it returns.

With the plain callback:

web3.eth.getBalance(address, (err, balance) => {
    if (err) {
        console.log(err);
        // do something here upon error
        return;
    }
    const EthValue =  web3.utils.fromWei(balance, 'ether')
    const TotalEth = parseFloat(EthValue) * 4000;
    console.log(TotalEth);
    
    // use TotalEth here, not outside of the callback
  
});

Using the returned promise:

web3.eth.getBalance(address).then(balance => {
    const EthValue =  web3.utils.fromWei(balance, 'ether')
    const TotalEth = parseFloat(EthValue) * 4000;
    
    console.log(TotalEth);
    
    // use TotalEth here, not outside of the callback
}).catch(e => {
    console.log(e);
    // handle error here
});

Or, using await with the promise:

async function someFunction() {

    try {
        const balance = await web3.eth.getBalance(address);
        const EthValue =  web3.utils.fromWei(balance, 'ether')
        const TotalEth = parseFloat(EthValue) * 4000;
        
        console.log(TotalEth);
        
        // use TotalEth here, not outside of the callback
    } catch(e) {
        console.log(e);
        // handle error here
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading