Google Geocode API的回调函数没有立即执行
callback function for Google Geocode API not executing immediately
当我遍历这段代码时,我观察到的行为是:跳过响应处理程序代码,直到函数的其余部分完成,然后执行处理程序代码。这当然不是我想要的,因为响应之后的代码取决于响应处理程序中的代码。
var geocoder = new google.maps.Geocoder();
function initializePlaces() {
var destination_LatLng;
var destination = document.getElementById("destination_address").value;
geocoder.geocode( {'address': destination}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
alert("Bad destination address.");
} else {
alert("Error calling Google Geocode API.");
}
});
// more stuff down here
}
导致这种行为的原因是什么?我如何更改代码以确保回调在其下面的代码之前运行?
Geocode异步运行,因此您必须将该代码放入回调中,或者制作另一个回调函数:
geocoder.geocode( {'address': destination}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
alert("Bad destination address.");
} else {
alert("Error calling Google Geocode API.");
}
//put more stuff here instead
});
或
function moreStuff(){
//more stuff here
}
geocoder.geocode( {'address': destination}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
destination_LatLng = results[0].geometry.location;
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
alert("Bad destination address.");
} else {
alert("Error calling Google Geocode API.");
}
moreStuff();
});
相关文章:
- 如何做到这一点,使代码在不传递条件后执行函数
- javascript自执行函数-不同的语法
- JavaScript:只有当数组中的所有项都为true时才执行函数
- iFrame url更改时执行函数
- 为什么AngularJS在每个摘要循环上都执行函数
- 如何使用setInterval执行函数
- 当*ngFor以角度2结束时执行函数
- Ajax调用完成后如何执行函数
- 在显示引导弹出窗口之前执行函数
- 从自执行函数返回函数的Javascript性能命中率
- 在操作完成时执行函数
- jquery/js中的自执行函数
- 如何仅在完成对gap.client.youtube的请求.execute后执行函数
- 构造函数函数中的自执行函数的OO上下文/范围
- Javascript未使用=运算符执行函数
- AngularJS:如何按照预定义的顺序执行函数
- 在不使用隔离作用域的情况下执行函数的角度指令
- 如何在页面加载后执行函数是在 AngularJS 中完成的
- 完成页面加载后执行函数
- 如何在完成完全执行函数后触发循环