Javascript noob here. Apologies if there are a ton of duplicate questions out there because it seems like this must be a fundamental js function thing, but I honestly can't find an answer to this. I'm trying to wrap an API GET call in a function, and I'm running into behavior that I don't understand. The code in question:
I'm using the node-rest-client package to call the mapquest geocoding API. I'm interested in the lat/long data only.
var Client = require('node-rest-client').Client;
If I make the GET call like this, I can access parsed
as an object, which is what I want.
var address = 'New York'
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
// parsed == {lat, long}
But if I wrap this in a function:
function geocode(address){
var client = new Client();
var parsed;
client.get("http://www.mapquestapi.com/geocoding/v1/address?" +
'key=' + mapquestKeys.consumer_key +
'&location=' + address,
function(data, response) {
parsed = data.results[0].locations[0].latLng
}
);
return parsed
}
var address = 'New York'
parsed = geocode(address);
// parsed === undefined
parsed
doesn't seem to be affected by the inner function; it's undefined. How can I return parsed
as an object containing the data I want as in the first example? What the heck is going on here?