0

Forgive my ignorance, but I've been bashing my head against the wall on this for two days now. I'm looking to make a request to a website and then do stuff with that data.

I've isolated my problem to the following: I pull the data with Request, but it doesn't seem to 'hold on' to the data. If I run the following code:

request = require('request');
request('https://api.btcmarkets.net/market/BTC/AUD/orderbook', function (error, response, body) {
          let orderBookRequest = JSON.parse (body);
          console.log(orderBookRequest);
        });

This returns data, all is good with the world. But when I try to call the orderBookRequest outside of this function, the variable is not defined. As in this:

request = require('request');
request('https://api.btcmarkets.net/market/BTC/AUD/orderbook', function (error, response, body) {
          let orderBookRequest = JSON.parse (body);
        });
        console.log(orderBookRequest);

Edit: Having done further reading, I don't think it's about synchronicity, but about block scope. Because running this:

request = require('request');
let orderBookRequest = undefined;

request('https://api.btcmarkets.net/market/BTC/AUD/orderbook', function (error, response, body) {
          let orderBookRequest = JSON.parse (body);
         });

setTimeout(function(){ console.log(orderBookRequest); }, 5000);

Still returns undefined.

I've been Googling and playing around, with no luck. What am I doing wrong?

Thanks in advance.

randouser
  • 97
  • 10
  • Why not declare 'let orderBookRequest = undefined' at the first line, then try again? – Sphinx Jan 27 '18 at 00:36
  • 1
    See the marked duplicate, but you are also having a separate problem that you declared the variable inside the function making it a local variable only. It isn't going to exist outside it. – Patrick Evans Jan 27 '18 at 00:37
  • In your cb, should be `orderBookRequest = JSON.parse(body);` to assign the var to the outside scoped variable, don't use let in the cb as it scopes it to inside the cb only. – Christopher Marshall Jan 30 '18 at 20:53
  • 1
    That is *precisely* the answer I have been looking for a week now. I knew it had to be simple, but without the vocabulary to even articulate the problem, was unable to find anything helpful on google. Thanks so much. – randouser Feb 01 '18 at 12:46

0 Answers0