Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript函数返回未定义但工作正常的警报_Javascript_Php_Function_Google Maps_Es6 Promise - Fatal编程技术网

javascript函数返回未定义但工作正常的警报

javascript函数返回未定义但工作正常的警报,javascript,php,function,google-maps,es6-promise,Javascript,Php,Function,Google Maps,Es6 Promise,我正在使用google map api,其中有一个函数,我在其中传递地址,该函数返回纬度和经度,但在此代码中,函数返回我未定义,但当我使用alert而不是return时,它工作正常,请告诉我在这段代码中哪里出错。 我在过去的ajax代码中也遇到过同样的问题,但我使用了async=false 函数GetLocation(地址){ var geocoder=new google.maps.geocoder(); geocoder.geocode({'address':address},函数(结果

我正在使用google map api,其中有一个函数,我在其中传递地址,该函数返回纬度和经度,但在此代码中,函数返回我未定义,但当我使用alert而不是return时,它工作正常,请告诉我在这段代码中哪里出错。 我在过去的ajax代码中也遇到过同样的问题,但我使用了async=false


函数GetLocation(地址){
var geocoder=new google.maps.geocoder();
geocoder.geocode({'address':address},函数(结果,状态){
if(status==google.maps.GeocoderStatus.OK){
var latitude=results[0]。geometry.location.lat();
var longitude=results[0]。geometry.location.lng();
返回经度;
//警报(“纬度:“+纬度+”\n纬度:“+经度”);
//返回纬度;
}否则{
返回“请求失败。”;
} 
});
};  
var abc=获取位置(地址);
警报(abc);
您的
geocode()
是一个异步调用,无法从中返回内容。因此,您需要继续您的逻辑,这取决于回调函数中的结果

或者您需要使用,并更改一些逻辑以实现结果。但再次承诺你不能从中得到任何回报|

在这段代码中,您从函数中创建了一个返回a
Promise
Promise
将使用2个功能,一个是如果一切都正常,另一个是如果出现问题。如果一切正常,则使用参数调用它。在
Promise
上,您可以调用
.then()
函数并向其中传递两个函数:第一个函数将作为
解析函数
传递,第二个函数作为
拒绝函数
。因此,在本例中,当您调用
resolve
时,它会将参数传递给
的第一个函数。然后()
,您就可以在那里得到它

函数GetLocation(地址){ 返回新承诺(函数(解析、拒绝){ var geocoder=new google.maps.geocoder(); geocoder.geocode({'address':address},函数(结果,状态){ if(status==google.maps.GeocoderStatus.OK){ var latitude=results[0]。geometry.location.lat(); var longitude=results[0]。geometry.location.lng(); 分辨率(经度); }否则{ 拒绝(“请求失败”); } }); }); }; 变量地址='yourAddress'; GetLocation(地址),然后(经度=>alert(经度))