geocoder.geocode 接受一个回调函数,执行异步,然后在有结果时调用回调。
这意味着getLocationName在回调被调用之前返回,并且由于没有return语句它返回undefined。
return results[1].formatted_address; 从回调中返回 formatted_address,而不是从 getLocationName!
(results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
return results[1].formatted_address; //This returns from this callback
}
}
}
这可以通过(通常是邪恶的)setTimeout 伪造异步请求来证明:
function callMe(value) {
setTimeout(function() { return value; }, 3000);
return "This is not the value";
}
var result = callMe("This is the value");
console.log(result);
https://jsfiddle.net/cok3h4tn/1/
您可以看到“这不是值”正在打印,因为return "This is not the value"; 是返回值,而不是return value;。
这里是google maps sample for geocoding,你可以看到它如何在回调中使用结果,而不是试图返回它。
或者,这是另一个如何使用回调的示例:
以此示例代码为起点。
它不起作用,但它是一个起点。
function callMe(value) {
setTimeout(function() { return value; }, 3000);
return "This is not the value";
}
var result = callMe("This is the value");
console.log(result);
callMe 被调用,然后我们想要获取结果,并对其进行处理。
我们可以用另一种方式写这个,我们想要对结果做的“某事”在它自己的函数handleResult中。
function handleResult(result) {
console.log(result);
}
function callMe(value) {
setTimeout(function() { return value; }, 3000);
return "This is not the value";
}
var result = callMe("This is the value");
handleResult(result);
现在这仍然不正确,因为“错误”结果仍在传递给handleResult。
因此,我们需要进行更改,将“正确”结果传递给handleResult。
function handleResult(result) {
console.log(result);
}
function callMe(value) {
setTimeout(function() { handleResult(value); }, 3000);
return "This is not the value";
}
callMe("This is the value");
更新 jsfiddle:https://jsfiddle.net/cok3h4tn/4/