0

It's my first question.

So, I'm using NodeJS + Express.

Here's my code:

request(urlPrice, function(err, resp, body){
    priceInfo = JSON.parse(body),
    medianPrice = priceInfo.median_price,
    changePrice = medianPrice.replace(',','.'),
    finallyPrice = parseFloat(changePrice).toFixed(2);
});

console.log(finallyPrice);

What can I do? Because, in console.log() the finallyPrice variable is undefined.

Please, help me.

Adam Boduch
  • 11,023
  • 3
  • 30
  • 38

2 Answers2

0

Try this, the variables are set only in the request callback handler

request(urlPrice, function(err, resp, body){
    priceInfo = JSON.parse(body),
    medianPrice = priceInfo.median_price,
    changePrice = medianPrice.replace(',','.'),
    finallyPrice = parseFloat(changePrice).toFixed(2);
    console.log(finallyPrice);
});
kiran
  • 374
  • 1
  • 7
  • Yes I know this work. But I need to use finallyPrice variable outside a request. Your solution works and I have context from json. I want to use finallyPrice variable outside a request then this don't work.I want to repair this and i don't have an idea how. – Robert Wozniak Jul 10 '15 at 17:43
  • What do you mean by outside the request. you mean another request? Since its a web application, I am assuming you are only dealing with requests. – kiran Jul 10 '15 at 17:45
  • Thanks for help, it was synchronous web request. – Robert Wozniak Jul 10 '15 at 19:39
0

Im guessing you want access to the finallyPrice variable outside the actual request portion of your app.

To do this, you will have to export your objects so that they can be accessed outside the scope of the function they are defined in. This is how to pass variables back and forth in Node: https://nodejs.org/api/modules.html#modules_module_exports. For a beginner post explaining how this all works, you may want to check out this: http://openmymind.net/2012/2/3/Node-Require-and-Exports/

Jonathan Kempf
  • 699
  • 1
  • 13
  • 27