NodeJS从开放式汇率回调中分配本地变量

时间:2015-08-29 19:10:39

标签: javascript node.js rest callback scope

考虑我从REST API GET请求执行的以下方法。我正在使用他们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); }

问题是我的目标是从这个函数返回jsonObj对象,意图在oxr.latest回调中分配它们各自的值。

但是这种方法之外仍然是空的。如何确保在其他方面正确分配jsonObj以从findLatestRate(params)函数返回它?

0 个答案:

没有答案