Skip to content

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.

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

Answer

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