Search code examples
node.jsnpm

Access variable from NPM outside of NPM internal function


I'm trying to access a variable that runs via npm. I can get the variable directly in the function, but I can't seem to pass it outside using callbacks or returning it, etc..

This is what I'm trying to do:

const binance = require("./binance.js");

async function getBalance() {
  var balance;
  binance.balance((error, balances) => {
    if ( error ) return console.error(error);
    console.info("USDT Test balance: ", balances.USDT.available);
    data = balances.USDT.available;
  })
  balance = data;
  console.log("Balance: ", balance);
  return balance;
}


getBalance(function (data) {
  console.log("USDT Actual balance: ", Math.round(data));
})

module.exports = getBalance;

I cannot get either the "Balance" or the "USDT Actual balance" to console log, which means I am not getting the variable in the return. I am getting the test balance fine.

Here is the the file I am using the export in:

const getBalance = require('./module1');

async function getBalanceData() {
  try {
    const tBalance = await getBalance();
    console.log("Budget:", tBalance);
    return tBalance;
  } catch (error) {
    console.error("Error fetching budget:", error);
  }
}
 getBalanceData().then((tBalance) => {
 console.log("Try getting the balance here:",tBalance);
 })


And here is the repsonse:
Budget: undefined
Try getting the balance here: undefined

Solution

  • Since binance.balance is apparently a callback-based async function, you need to use the new Promise pattern to promisify it (or, well, util.promisify works too in Node.js land, but this is how you'd do it by hand):

    const binance = require("./binance.js");
    
    async function getBalance() {
      return new Promise((resolve, reject) => {
        binance.balance((error, balances) => {
          if (error) return reject(error);
          console.info("USDT Test balance: ", balances.USDT.available);
          resolve(balances.USDT.available);
        });
      });
    }
    
    async function getBalanceData() {
      try {
        const tBalance = await getBalance();
        console.log("Budget:", tBalance);
        return tBalance;
      } catch (error) {
        console.error("Error fetching budget:", error);
      }
    }
    
    getBalanceData().then((tBalance) => {
      console.log("Try getting the balance here:", tBalance);
    })