简体   繁体   中英

Javascript return statement not executing - Function flow

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)

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)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM