0
$("#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()
});
1
  • What is the question? Commented Dec 19, 2024 at 15:27

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.