我有这个功能。我似乎不明白它是如何工作的。因为我想使用此函数返回returnlatlang
。但它根本行不通。
var geocoder = new google.maps.Geocoder();
function codeAddress(address) {
var returnlatlang;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
returnlatlang = results[0].geometry.location;
console.log(returnlatlang); // this is defined.
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
console.log(returnlatlang); // this is undefined.
return returnlatlang;
}
在这种情况下,范围如何运作?
答案 0 :(得分:0)
codeAddress
在异步函数能够设置之前返回变量returnlatlong
。
你可以使用Promise,一个基本的例子就是这样:
function codeAddress(address){
return new Promise(function(resolve, reject){
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
returnlatlang = results[0].geometry.location;
resolve(returnlatlang); // this is defined.
} else {
reject('Geocode was not successful for the following reason: ' + status);
}
});
}
codeAddress('some address').then(function(){
//the promise resolved
}, function(){
//the promise rejected
});