繁体   English   中英

JavaScript return语句未执行-功能流程

[英]Javascript return statement not executing - Function flow

我有一个函数,如下所示,这看起来很逻辑,但是运行时返回UNDEFINED。

该程序应该返回下面的地址字符串,但是代码未按正确的顺序运行。 谁能提供有关我如何改善程序流程的反馈?

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)

您在函数中做错的两件事:

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

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

当调用该函数时,您将获得一个promise,如果它在异步函数中使用,则可以使用await或仅使用promise.then方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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