0

in this case I would like to access to data:

const request = require('request');
const { url } = require("inspector");


request(`https://api.0x.org/swap/v1/tokens`, { json: true }, (err, res, body) => {
    if (err) { return console.log(err); 
        
    }
    let data = body;

    
    
});


console.log(data) 

console.log(data) return ReferenceError: data is not defined

Laurent
  • 43
  • 1
  • 6
  • The immediate explanation for your error is that `data` is block scoped and only exists within your callback function. Outside it, it "doesn't exist" as far as the interpreter is concerned. The bigger issue here is that you're trying to access asynchronous data in a synchronous manner. Your call to `request` takes time and data is not immediately available, that is why you use a callback in the first place. Refer to the duplicate-it gives a pretty good overview of the why and the how to fix. – Andrew Li Nov 24 '20 at 21:07

1 Answers1

-1

You cannot access data unless you were to define it outside of your function. Update the variable data within your function via this.data = body;

Something like this.

const request = require('request');
const { url } = require("inspector");
let data = "";

request(`https://api.0x.org/swap/v1/tokens`, { json: true }, (err, res, body) => {
    if (err) { return console.log(err); 
        
    }
    this.data = body;
});


console.log(this.data) 
edjm
  • 4,830
  • 7
  • 36
  • 65
  • You should not be using global `this`. In strict mode it's even undefined instead of the global scope. You're also still trying to use asynchronous data in a synchronous manner. – Andrew Li Nov 24 '20 at 21:03