Javascript 我可以警告该值,但不能作为函数的值返回
我想从函数中返回一个值。当我在外部调用函数时,没有返回任何内容,只是提醒'res'变量,它会提醒ok。但是当我从函数返回res变量,然后通知整个函数时,它会通知“undefined”。为什么会发生这种情况? 我想再次提到,当我向res变量发出警报时,一切警报都正常,只是我无法从函数返回Javascript 我可以警告该值,但不能作为函数的值返回,javascript,function,functional-programming,Javascript,Function,Functional Programming,我想从函数中返回一个值。当我在外部调用函数时,没有返回任何内容,只是提醒'res'变量,它会提醒ok。但是当我从函数返回res变量,然后通知整个函数时,它会通知“undefined”。为什么会发生这种情况? 我想再次提到,当我向res变量发出警报时,一切警报都正常,只是我无法从函数返回 function geocodeLatLng(location, method) { var res; var geocoder = new google.ma
function geocodeLatLng(location, method) {
var res;
var geocoder = new google.maps.Geocoder;
geocoder.geocode(method, function(results, status) {
if (status === 'OK') {
if (results[0]) {
if(method.address){
res = results[0].geometry.location
var marker = new google.maps.Marker({
position: res,
draggable:true,
map: map
});
}
else {
res = results[0].formatted_address
}
show_road(results[0].geometry.location);
} else {
window.alert('good');
}
} else {
window.alert('wrong: ' + status);
}
});
return res;
}
alert (geocodeLatLng(center, {'location': center}));
geocoder.geocode
异步执行并接受回调
回调只调用一次geocoder.geocode
已完成。由于它是异步工作的,因此在从回调中实际设置res
之前执行return res
一个简单的解决方法是使用async/await
,并承诺包装异步函数:
async function geocodeLatLng(location, method) {
var geocoder = new google.maps.Geocoder;
return await new Promise((resolve, reject) => {
let res;
geocoder.geocode(method, function(results, status) {
if (status === 'OK') {
if (results[0]) {
if(method.address){
res = results[0].geometry.location
var marker = new google.maps.Marker({
position: res,
draggable:true,
map: map
});
}
else {
res = results[0].formatted_address
}
show_road(results[0].geometry.location);
} else {
window.alert('good');
}
} else {
window.alert('wrong: ' + status);
}
resolve(res);
});
});
}
(async () => {
const result = await geocodeLatLng(center, {'location': center});
alert(result);
})();
非常感谢。它解决了这个问题,但是你能帮助我如何将返回值分配给变量吗。没有提醒它。我似乎无法分配我已经修改了我的答案。结果现在分配给变量
result
。要使用它,您需要在匿名异步函数中。