Home > Back-end >  I am trying to assign value to varibale outside of callback function but it is not assigning value a
I am trying to assign value to varibale outside of callback function but it is not assigning value a

Time:03-02

So basically I am writing one program where I am converting values from one currency to another. My function looks like this, I am using OpenExchangeRates API to get value Package doc is this. and fx is a submodule of OXR which is this

async function convertToAnotherCurrency(base, toConvert, amountToBeConverted) {
  var convertedValue;
  await oxr.latest(async () => {
    fx.rates = oxr.rates;
    fx.base = oxr.base;
    convertedValue = await fx(amountToBeConverted).from(base).to(toConvert);
    console.log(convertedValue); //this is logging expected response
  });
  console.log(await convertedValue); // this is showing undefined
}

Can anyone help me figure out what I am doing wrong or help me with suggestions?

Thank you in advance.

CodePudding user response:

You are getting this issue as latest method from open-exchange-rates is not giving you a promise. Below will solve your issue:

const fx = require("money");
const { promisify } = require("util");
const oxr = require("open-exchange-rates");

const oxrLatestPromisify = promisify(oxr.latest);

oxr.set({ app_id: "your_app_id" });

async function convertToAnotherCurrency(base, toConvert, amountToBeConverted) {
  var convertedValue;

  await oxrLatestPromisify();

  fx.rates = oxr.rates;
  fx.base = oxr.base;

  convertedValue = await fx(amountToBeConverted).from(base).to(toConvert);

  console.log(convertedValue);
}
  • Related