Reputation:
$("#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()
});
Upvotes: 0
Views: 442
Reputation: 322502
If geo.geocode()
is an AJAX request, then the code that comes after it does not wait for the response to return before it executes.
As such, the code runs out of order. The second alert()
fires, because there's nothing to prevent it from firing. The first one fires when the AJAX response is received.
If you have some other code that relies on the response, then place that code in a function, and call it from inside the callback for 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)
}
Upvotes: 3
Reputation: 887449
The geocode
function is asynchronous.
The callback that you pass it runs some time after the call to geocode
; the geocode
function itself does not (and cannot) wait for a response.
Upvotes: 4
Reputation: 186562
Probably because the other one is in a callback? It depends on what .geocode
does with it, but most likely it could be an ajax callback.
Upvotes: 0