Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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"
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
    }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!