-1

I have currently following code:

var request = require('request');

var variable1;

request('https://api.coindesk.com/v1/bpi/currentprice/EUR.json', function (error, response, body){
    var btceurpricejson = (body);
    var obj = JSON.parse(btceurpricejson);
    variable1 = (obj.bpi.EUR.rate_float);
});

function getBTCItemPrice() {
        console.log(variable1);
};

getBTCItemPrice();

But it always only outputs undefined. When I use console.log(variable1); in the request function, it works. But when I use it like above, in another function, it doesn't work. Even though I use a global variable.

Thank you in advance!

  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – jonrsharpe Nov 28 '18 at 08:16
  • Simply saying, when you create a variable and leave it without assigning a value to it, JavaScript will automatically assign a value called undefined. – ArunPratap Nov 28 '18 at 08:18

2 Answers2

1

This should work call your function in your request callback.

var request = require('request');

var variable1;

request('https://api.coindesk.com/v1/bpi/currentprice/EUR.json', function (error, response, body){
    var btceurpricejson = (body);
    var obj = JSON.parse(btceurpricejson);
    variable1 = (obj.bpi.EUR.rate_float);
    getBTCItemPrice();
});

function getBTCItemPrice() {
        console.log(variable1);
};
SAGAR RAVAL
  • 319
  • 1
  • 9
1

Its a bad practice to use global. But as said above calling getBTCItemPrice() inside the callback will serve your purpose.

Sashk26
  • 11
  • 3
  • Yea thanks, now that that worked, I was able to use `getBTCItemPrice(variable1);` and `function getBTCItemPrice(variable1) { console.log(variable1); };` So that means, I don't longer need a global variable. – Preisschild Nov 28 '18 at 10:26