Skip to content
Advertisement

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:

JavaScript

In the console I get the below output.

JavaScript

Advertisement

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:

JavaScript

Using the returned promise:

JavaScript

Or, using await with the promise:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement