[英]Using inner function variable in outer function using Google Maps Javascript API
I am fairly new to Javascript so forgive me if this has been answered but I cannot get this to work nor can I find the answer anywhere online.我对 Javascript 相当陌生,所以如果这个问题已经得到解答,请原谅我,但我无法让它工作,也无法在网上的任何地方找到答案。 I am trying to return an address using Google's Maps JavaScript API.我正在尝试使用 Google 的地图 JavaScript API 返回地址。 I can print it to the console inside the inner function but if I try to access it outside of that function, it is printing undefined.我可以将它打印到内部 function 内的控制台,但如果我尝试在 function 之外访问它,它正在打印未定义。 How can I access the variable in the outer function and return it??如何访问外部 function 中的变量并返回它?
function getAddress(latlng) {
var address;
var service = new google.maps.Geocoder();
service.geocode({ location: latlng}, function(results, status) {
if (status === "OK") {
if (results[0]) {
address = results[0].formatted_address;
console.log(address); //prints address
}
}
});
console.log(address); //prints undefined
}
The issue is a classic asynchronous gotcha, where address
is available only once the callback is invoked, where usually, when a callback is needed, it means there are no guarantees its result will be available outside its execution, and since I believe there is a network request involved, there's no way the result can arrive in time for you to log address
right after.问题是一个经典的异步陷阱,其中address
仅在调用回调后才可用,通常,当需要回调时,这意味着不能保证其结果在其执行之外可用,并且因为我相信有一个涉及网络请求,结果无法及时到达让您立即登录address
。
var value;
api.thing(callbackThatSetsValue)
console.log(value);
The gits of the problem is there: value
can't point at anything, as the callbackThatSetsValue
will be invoked after the next line of code gets executed.问题的根源就在那里: value
不能指向任何东西,因为callbackThatSetsValue
将在下一行代码执行后被调用。
There are at least 2 options here, let's see how these look like...这里至少有 2 个选项,让我们看看它们的样子……
Wait for the result等待结果
This options allows you to do anything you need once the address is resolved.此选项允许您在解析地址后执行任何您需要的操作。
function getAddress(latlng, after) {
var service = new google.maps.Geocoder();
service.geocode({ location: latlng}, function(results, status) {
if (status === "OK")
if (results[0])
after(results[0].formatted_address);
});
}
Above utility allows you to getAddress({lat:50,lng:1}, console.log)
, as example, or pass any callback that should render, use, display, such address.上面的实用程序允许您getAddress({lat:50,lng:1}, console.log)
,例如,或传递应该呈现、使用、显示此类地址的任何回调。
The pitfall in this approach is that if status
is not OK
, you have a hanging callback forever, as it won't ever get invoked.这种方法的缺陷是,如果status
不是OK
,您将永远有一个挂起的回调,因为它永远不会被调用。
Alternatively, you can put an else
in that function and pass an error, or null
, and react accordingly in the callback.或者,您可以在 function 中放置一个else
并传递一个错误,或者null
,并在回调中做出相应的反应。
The Promise way Promise方式
Is the most common pattern these days, hence my suggestion.是这些天最常见的模式,因此我的建议。
function getAddress(latlng) {
return new Promise(function ($, _) {
var service = new google.maps.Geocoder();
service.geocode({ location: latlng}, function(results, status) {
if (status === "OK")
if (results[0])
$(results[0].formatted_address);
_(new Error("status was " + status));
});
});
}
In this case you getAddress({lat:50,lng:1}).then(console.log).catch(console.error)
, so you have an escape/way to react when address is not valid.在这种情况下,您getAddress({lat:50,lng:1}).then(console.log).catch(console.error)
,因此当地址无效时您有一种转义/反应方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.