0

I'm having an issue with the scope of a variable. I need to be able to access "userLocation" outside of "request". The request package can be found at https://github.com/request/request Here's my code below:

var request = require('request');  
var userLocation = "";  
request('http://ipinfo.io', function(error, res, body) {  
    var ipDetails   = JSON.parse(body);  
    userLocation    = ipDetails.loc;  
});  
console.log(userLocation);

When I try to output the "userLocation" variable, it prints an empty string instead of the details from the request package.

dnesbeth
  • 1
  • 1

1 Answers1

1

It's not a scope issue. The nature of NodeJS is asynchronous, meaning that console.log(userLocation) will not wait your request to be completed before it executes. That's why promises and callback functions exist.

If you want to print userLocation, move it inside the callback function like so:

var request = require('request');  
var userLocation = "";  
request('http://ipinfo.io', function(error, res, body) {  
    var ipDetails = JSON.parse(body);  
    var userLocation = ipDetails.loc;  
    console.log(userLocation);
});  

Take a look at this awesome tutorial if you wish to learn more.

tiagodws
  • 1,345
  • 13
  • 20
  • Hi, thanks for the reply. What if I need to assign the value from "request" to a variable outside of the request function? – dnesbeth Jul 09 '17 at 19:40
  • Would a Promise work for you ? new Promise((res, rej) => { var resolve = function (myReqValue){ res(myReqValue); } request('http://ipinfo.io', function(error, res, body) { var ipDetails = JSON.parse(body); var userLocation = ipDetails.loc; resolve(userLocation); }); }).then((res) => { console.log("Userlocation: " + res) }); – midnightsyntax Jul 09 '17 at 19:57
  • @midnightsyntax thanks! that worked perfectly. – dnesbeth Jul 09 '17 at 20:32