$("#btnsub").click(function () {
var add = $("#txtname").val();
var obj;
var geo = new google.maps.Geocoder;
geo.geocode({ 'address': add }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
obj = results[0].geometry.location;
obj = convert(obj);
alert(obj);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
alert(obj);
// why this alert run first instead of the upper alert()
});
geocode
函数是异步。
您传递给它的回调会在调用
geocode
之后运行一段时间; geocode
函数本身不会(也不能)等待响应。
如果
geo.geocode()
是AJAX请求,那么after出现的代码不会等待响应返回就执行。
因此,代码运行不正常。第二个
alert()
会触发,因为没有什么可以阻止它触发。第一个在收到 AJAX 响应时触发。
如果您有一些依赖于响应的其他代码,则将该代码放入函数中,并从回调内部调用它以实现
geo.geocode()
。
$("#btnsub").click(function () {
var add = $("#txtname").val();
var obj;
var geo = new google.maps.Geocoder;
geo.geocode({ 'address': add }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
obj = results[0].geometry.location;
obj = convert(obj);
alert(obj);
// Call a function that relies on the response
// and pass the obj to it.
someOtherFunction( obj );
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
function someOtherFunction( data ) {
alert( data );
// do something with the obj (referenced as data)
}
可能是因为另一个正在回调?这取决于
.geocode
用它做什么,但最有可能的是 ajax 回调。