What's the best way to implement these functions using a variable?

I am looking to store the output of these functions in a variable so that I can reuse them later in my code

 function sellPrice() {
        contract.sellPrice(function(err, result) {
            if(err) {
                console.log(err, 'err');
            } else {
                document.getElementById('sellPrice').innerHTML = result/100000000;
            }
        });
    } sellPrice();

However, I can only access the (result) inside the function and would like to use it further down in my code.

Is there a way for me to access the result of sellFunction()?

Below is my code:

const address = '0xE462CbEE0cd420f6c199B0194B1D8D93Fb5e7720';
// GLOBALS
const web3Mode = null
const walletMode = 'connect'
const currentAddress = null
const keystore = null
const dividendValue = 0
const tokenBalance = 0
//const contract = null
const abi = [{"constant":true,"inputs":[{"name":"_customerAddress","type":"address"}],"name":"dividendsOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_agiToSpend","type":"uint256"}],"name":"calculateTokensReceived","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_tokensToSell","type":"uint256"}],"name":"calculateAgiReceived","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"onlyAmbassadors","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs...

const contract = web3.eth.contract(abi).at(address);



window.addEventListener('load', async function() {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    var web3;
    var globalState = {};

    console.log(web3, 'web3');
    if(window.ethereum) {
        web3 = new Web3(window['ethereum']);
        try {
            // Request account access if needed
            await window.ethereum.enable();

            web3.eth.getAccounts(function (error, accounts) {
                document.getElementById('account-address').innerHTML = accounts[0];
            });

            // Acccounts now exposed
            window.ethereum.on('accountsChanged', function () {
                web3.eth.getAccounts(function (error, accounts) {
                    document.getElementById('account-address').innerHTML = accounts[0];
                });

                window.ethereum.on('connect', function () {
                    //    console.log('connect');
                });
            });
        } catch (error) {
            console.error(error);
        }
    } else if (window.web3) {
        console.log(2);
        // Legacy dapp browsers...
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
    } else {
        console.log(3);
        // Fallback to localhost; use dev console port by default...
        const provider = new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/9bee77f147884c73bb2852e269dacece');
        web3 = new Web3(provider);
    }

    function sellPrice() {
        contract.sellPrice(function(err, result) {
            if(err) {
                console.log(err, 'err');
            } else {
                document.getElementById('sellPrice').innerHTML = result/100000000;
            }
        });
    }


    function buyPrice() {
        contract.buyPrice(function(err, result) {
            if(err) {
                console.log(err, 'err');
            } else {
                document.getElementById('buyPrice').innerHTML = result/100000000;
            }
        });
    }
    buyPrice();

    function totalSupply() {
        contract.totalSupply(function(err, result) {
            if(err) {
                console.log(err, 'err');
            } else {
                document.getElementById('contractBalanceSnet').innerHTML = result/100000000 + ' SNET';
            }
        });
    }
    totalSupply();

    function balanceOf() {
        web3.eth.getAccounts(function (error, accounts) {
            contract.balanceOf(accounts[0], function(err, result) {
                if(err) {
                    console.log(err, 'err');
                } else {
                    document.getElementById('snet-holding').innerHTML = result/100000000;
                    console.log(result);
                }
            });
        });
    }
    balanceOf();

    function totalAgiBalance() {
        web3.eth.getAccounts(function (error, accounts) {
            contract.totalAgiBalance( function(err, result) {
                if(err) {
                    console.log(err, 'err');
                } else {
                    document.getElementById('agiContractBalance').innerHTML = result/100000000 + ' AGI';
                    console.log(result);
                }
            });
        });
    }
    totalAgiBalance();

    function myDividends() {
        web3.eth.getAccounts(function (error, accounts) {
            contract.myDividends(accounts[0], function(err, result) {
                if(err) {
                    console.log(err, 'err');
                } else {
                    document.getElementById('myDividends').innerHTML = result/100000000 + ' AGI';
                    console.log(result);
                }
            });
        });
    }
    myDividends();
}); //end of first stuff



var tokenAddress = '0xb97E9bBB6fd49865709d3F1576e8506ad640a13B';
var walletAddress = '0x62f28320f688A7A4e0021c55d7ffD1acd770A133';



    function getERC20TokenBalance() {

      let minABI = [
        // balanceOf
        {
          "constant":true,
          "inputs":[{"name":"_owner","type":"address"}],
          "name":"balanceOf",
          "outputs":[{"name":"balance","type":"uint256"}],
          "type":"function"
        },
        // decimals
        {
          "constant":true,
          "inputs":[],
          "name":"decimals",
          "outputs":[{"name":"","type":"uint8"}],
          "type":"function"
        }
      ];

      let contract2 = web3.eth.contract(minABI).at(tokenAddress);

      web3.eth.getAccounts(function (error, walletAddress) {
          contract2.balanceOf(walletAddress, function(err, result) {
              if(err) {
                  console.log(err, 'err');
              } else {
                console.log(result);
                  document.getElementById('agiAvailable').innerHTML = result + ' AGI';

              }
          });
      });
    }getERC20TokenBalance();


    function onAddressChange(e) {

      if(tokenAddress != "" && walletAddress != "") {
        getERC20TokenBalance(tokenAddress, walletAddress, (balance) => {
          console.log(balance.toString());
        });
      }
    }

I hope to achieve something similar to this:

function sellPrice() {
        contract.sellPrice(function(err, result) {
            if(err) {
                console.log(err, 'err');
            } else {
                return (result);
            }
        });
    }
    document.getElementById('sellPrice').innerHTML = sellPrice();

Answer №1

/* The function below utilizes a Promise to handle the selling price logic */

function calculateSellingPrice() {
       var resolve, reject;
       var pricePromise = new Promise(function(resolveFunc, rejectFunc) {
          resolve = resolveFunc;
          reject = rejectFunc;
       });
        contract.getSellingPrice(function(error, result) {
            if(error) {
                console.log(error, 'error');
                reject(error);
            } else {
                document.getElementById('sellingPrice').innerHTML = result/100000000;
                resolve(result);
            }
        });
        return pricePromise;
    }

var priceCalculation = calculateSellingPrice();
priceCalculation.then(function(result) {

  console.log("Result obtained= " + result);
});

priceCalculation.catch(function(error) {
  console.log("Error occurred= " + error);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to minify HTML in PHP without parsing JavaScript and CSS code?

After finding a solution in this discussion, I successfully managed to 'minify' HTML content. function process_content($buffer) { $search = array( '/\>[^\S ]+/s', // eliminate spaces after tags, except for ...

Mobx's usage in React Router 4 causes the component to be reinitialized

I am currently using react router v4 alongside mobx, and I've encountered an irritating bug. Here's my index.js: const history = createHashHistory(); render( <Provider history={history} {...stores}> <Router history={ ...

What is the process for generating a printable report using HTML, CSS, and ASP.NET Core?

I am looking to create a customizable report using HTML and CSS, however I am not familiar with designing forms like pay slips that can be easily printed. Please see the images I have shared below for reference. Any help or guidance would be greatly apprec ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

React: The arrow function is expecting a return value in the form of an array callback

I'm encountering an issue with the following snippet of code where I keep getting an error message stating that Arrow function expected a return value array-callback-return. Despite attempting to troubleshoot, I am unable to pinpoint the exact problem ...

Having trouble initiating a "curl:localhost:3000" connection, receiving a URI Error message

Recently delving into the realm of node js, I have embarked on a journey to start up a server and experiment with an app designed to trim URLs. However, I find myself at an impasse. Environment: Windows Text Editor: VSCode Below is my code for index.js ...

WebPack bundling causing issues with Knockout Validation

I am developing a web application using Knockout along with the Knockout-Validation plugin, and I want to utilize WebPack for bundling. However, I encountered an issue where Knockout-Validation seems to break when incorporated with WebPack. To illustrate ...

Avoiding repetition within a collection of objects

Currently navigating my way through learning Node and Mongoose, I am faced with the challenge of preventing duplicates in an array of ListItems: var listitemSchema = new mongoose.Schema({ name: String, rank: Number }); This array resides inside a u ...

Error occurred while trying to access a file within the server using $_GET method

Struggling to access a URL within my folder, but encountering an error. I have attempted using file_get_contents without success. Warning: include(/home/vol2_3/*****/*****/htdocs/new/td.php?r=8&ids=309834): failed to open stream: No such file or direct ...

Update the content within every <td> element using AJAX/JQUERY on a table created from JSP

I have a database filled with descriptions and corresponding ID numbers. The table displays them like this: index.jsp <table> <tr> <td>Name:</td> <td>Id:</td> </tr> <c:forEach items ...

JavaScript button triggering image slider display

I am having difficulty with a slider containing URL links inside an Array. Can anyone help me figure out how to make this code run properly? Here is the link to the code: https://codepen.io/konradszymanski/pen/VwvLgYG?editors=0110 Below is the HTML: &l ...

Extending a line with additional characters

After reviewing the code snippet and description linked here: Add Bullets to Each New Line within a textarea const bullet = "\u002a"; const bulletWithSpace = `${bullet} `; const enter = 13; const handleInput = (event) => { const { ...

What is the proper method for terminating an Express app.all?

Here's a snippet of my code where I utilize the app.all method. In this scenario, I am invoking the fetchBuildings function based on the building ID or hash provided in the URL. Subsequently, I am assigning values to the title, description, and image ...

Is there a way to trigger js function calls upon the loading of my .js file?

How can I ensure that the following function calls are executed when the .js file is loaded? Layout.Controls.sidebar(Button.Add); Layout.Controls.sidebar(Button.Init); Layout.Controls.printScreen(Button.Add); Layout.Controls.theme(Button.Add); Layout.Cont ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

Oops! Looks like we ran into a bit of a snag with the process_metrics

During our recent Protractor tests, we have been encountering warnings in the console: [12252:14584:1207/223118.187:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [12252:14584:1207/223118.187:ERROR:process_metrics.cc(105)] NOT IMPLEMENTED [12252:14584:120 ...

At which location do you configure the applicationIconBadgeNumber?

Can anyone guide me on how to set up the applicationIconBadgeNumber for a React Native / Expo application on both iOS and Android platforms? I am currently using React Native, Visual Studio Code, and Expo. Where should I look to configure this feature? O ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response: { "statusCode": 200, "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F10645774 ...