0

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)
William Merritt
  • 429
  • 1
  • 5
  • 12
  • 4
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Luca Kiebel Apr 16 '18 at 18:00
  • 1
    FWIW: your top level function has no return statement. The only return statement is the arrow function you pass to .then() call (and so, naturally, it turns only from that arrow function). – Frax Apr 16 '18 at 18:11
  • 1
    You need to return newAddress from first call as well .then(res=> {return newAddress}) after console.log(newAddress); – Nish26 Apr 16 '18 at 18:18
  • @Nish26 could you elaborate on your solution? – William Merritt Apr 16 '18 at 18:58

1 Answers1

0

2 thing you did wrong in the function:

request(geocodeAddress).then(res => {
//should be:
return request(geocodeAddress).then(res => {

console.log(newAddress)
//should be:
console.log(newAddress);return newAddress

And when you call the function you will get a promise, if it's used in an async function you can use await or just use the promise.then method:

lat = 28.4177591;
lon = -81.5985051;
getAddress(lat, lon)
.then(
  result=>console.log("This IS NOT undefined: ",result ),
  error=>console.warn("something went wrong:",error)
)
HMR
  • 37,593
  • 24
  • 91
  • 160
  • your solution doesnt allow the result to be stored in a variable for later use. How would you modify it for this? – William Merritt Apr 16 '18 at 18:55
  • @WilliamMerritt `const useLater = getAddress(lat, lon)` and then later: `useLater.then(result=>...` – HMR Apr 17 '18 at 04:15