[英]Javascript Nested Function - Need help returning result
我正在尝试创建一个函数来从Google Maps JS API(v3)返回纬度/经度数组。 我可以写出从API检索到的数据,但不能将数据传递给变量。 我想做这样的事情:
var latLong = getLatLong(Address);
我创建的函数在这里:
function getLatLong(loc, callback) {
var geocoder = new google.maps.Geocoder();
var array = new Array();
if (geocoder) {
geocoder.geocode({ 'address': loc }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;;
$.each(latLng, function(k, v) {
if (k == 'va' || k == 'wa') {
array.push(v);
}
});
var ret = array;
callback(ret);
} else {
console.log("Geocoding failed: " + status);
}
});
}
}
然后,我将函数分配给一个变量,并调用它给我纬度/经度。
var geo = getLatLong('Dallas, TX', function(result) {
return result;
});
不幸的是,这会产生“不确定”的结果。 我可以在函数中访问结果,但是无法传递。 如何将函数的结果传递给要访问的变量?
不幸的是,这会产生“不确定”的结果
您是说'geo'变量吗? 如果是这样,则您错过了回调的要点。 传入的函数将在getLatLong()调用返回后稍后调用。 回调是异步函数,您将希望使用回调来执行您选择的操作(例如,更改状态,调整显示等)。
尝试将其更改为
function(result) { alert('callback result: '+result); }
检查它是否被正确调用。 如果您正确地获得了alert()
,则可能需要执行以下操作:
var geo = null;
getLatLong('Dallas, TX', function(result) {
// cache state
geo = result;
// do something with it
showResultInSomeSpotOnThePage(result);
});
/* We can't use the "geo" variable contents immediately
* after getLatLong returns; it will be set at some time later.
* But there may be some use for keeping the result around indefinitely,
* we just have to be prepared for "geo" to be null if we check it
* before the callback is called.
*/
您无法按照您想要的方式来构造代码。 问题在于geocoder.geocode()
是异步操作 。 这就是为什么它需要一个回调函数。 当您调用geocoder.geocode()
,它将启动获取地理编码的请求,然后返回,从而使请求在后台运行。 当请求最终完成时,Google的api将执行您作为第二个参数传递给geocode()
的匿名函数。
因此,当您调用getLatLong()
,事情发生的实际顺序是这样的:
geocoder.geocode()
。 (发起地址解析请求) getLatLong()
完成并返回未定义。 (这是设置geo
地方) array
,然后调用您的callback()
为了更好地可视化正在发生的事情,您可以按照以下方式编写代码(这完全等同于编写代码的方式):
function getLatLong(loc, callback) {
var geocoder = new google.maps.Geocoder();
var array = new Array();
function handleGeocodeResponse(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;;
$.each(latLng, function(k, v) {
if (k == 'va' || k == 'wa') {
array.push(v);
}
});
var ret = array;
callback(ret);
}
}
if (geocoder) {
geocoder.geocode({ 'address': loc }, handleGeocodeResponse);
} else {
console.log("Geocoding failed: " + status);
}
// note- no return specified explicitly is the same as
//return undefined;
}
那么,如果您不能返回值,那么如何使用结果呢? 像这样:
getLatLong('Dallas, TX', function(geo) {
// geo is passed to this function as a parameter
// move all code that requires `geo` into this function.
});
这里的关键点是getLatLong
不返回值。 这就是为什么geo
总是不确定的原因。
要使其工作,您需要修改回调函数。 像这样:
getLatLong('Dallas, TX', function(result)
{
var geo = result;
//continue to use geo here as you normally would
});
geo未定义,因为getLatLong()不返回任何内容(这意味着它将返回未定义)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.