I have a function, shown below, that seems logical, but returns UNDEFINED when ran.
The program is supposed to return address string below, but the code is not running in the right order. Could anyone provide feedback on how I can improve the programs flow?
function getAddress(lat, lon){
apiKey = "API-KEY";
geocodeAddress = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lon + "&key=" + apiKey;
const request = require('request-promise')
request(geocodeAddress).then(res => {
res = JSON.parse(res)
//res.results[0].formatted_address = "12345 White House, Washington, DC 12345 USA"
//Get rid of leading numbers/whitespace in address, only show street name
newAddress = res.results[0].formatted_address.replace(/^\d+\s*/, '');
//Get rid of Zip code and Country
newAddress = newAddress.split(',', 3).join(',').replace(/[0-9]/g, '').trim()
//newAddress- Returns: "White House, Washington, DC"
console.log(newAddress)
}).then((newAddress)=> {
//returns undefined
return newAddress
})
}
//Random 711
lat = 28.4177591;
lon = -81.5985051;
console.log("This returns undefined: ", getAddress(lat, lon))
var example2 = getAddress(lat, lon)
console.log("This also returns undefined: ", example2)