我有一个函数,如下所示,看似合乎逻辑,但在运行时返回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)
答案 0 :(得分:0)
你在函数中做错了2件事:
request(geocodeAddress).then(res => {
//should be:
return request(geocodeAddress).then(res => {
console.log(newAddress)
//should be:
console.log(newAddress);return newAddress
当您调用该函数时,您将获得一个承诺,如果它在异步函数中使用,您可以使用等待或只使用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)
)