Consider the following method that I execute from an REST API GET request. I am consuming the open-exchange-rates module as described in their documentation.
//This function will validate the received
//params and invoke the third
//party api call
function findLatestRate(params) {
//Break point
debugger;
// Result Variable
var jsonObj = {};
// Get latest exchange rates from API and pass to callback function
oxr.latest(function(err) { //node callback structure
if(err) {
//Print stack trace according to enviroment
console.log(
config.node_env === 'development' ?
err.toString() :
'Error occurred when trying to consume oxr API'
);
return false;
}
// Apply exchange rates and base rate to 'fx' library object:
fx.rates = oxr.rates; //Rates Currency from APU call
fx.base = oxr.base; //Base Currency from API call
//Prepare jsonObj according to params[IF IMPLEMENTING THE FOLLOWING CODE OUTSIDE THE CALLBACK, GET AN 500 ERROR FOR THE VERY FIRST TIME]
if(params.toCurrency && params.toCurrency in config.currencies_list) {
//prepare result for base currency to specified currency
jsonObj.baseCurrency = {
'fromCurrency': config.baseCurrency,
'amount': params.amount
};
jsonObj.toCurrency = {
'toCurrency': params.toCurrency,
'amountRate': fx(params.amount).from(config.baseCurrency).to(params.toCurrency)
};
} else {
jsonObj.statusCode = 400;
jsonObj.error = 'Bad request';
jsonObj.message = 'Only the following exchange currencies are available: ' +
Object.keys(config.currencies_list);
}
console.log('jsonObj within callback looks great: ' + JSON.stringify(jsonObj));
});
console.log('jsonObj outside callback still empty: ' + JSON.stringify(jsonObj));
return JSON.stringify(jsonObj); }
The problem is that I aiming to return the jsonObj object from this function intending to assign their respective values within the oxr.latest callback.
However outside of this method still empty. How can I ensure that jsonObj is properly assigned in other to return it from findLatestRate(params) function?