-1
function instate(loc)
{
    var a;
    var geocoder = new google.maps.Geocoder;
    var infowindow = new google.maps.InfoWindow
    geocoder.geocode({'location': loc}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(5);
            var arrAddress = results[0].address_components;
            $.each(arrAddress, function (i, address_component) {
              if (address_component.types[0] == "administrative_area_level_1"){
              a =  address_component.short_name;
              console.log(a);   
              }     
              //return false; // break the loop   
            });        
          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
    });
}

The code above can print out the right value of 'a' in console, but when I put the console.log(a) at the bottom of the function, just like below, it cannot print the right value and just print out "undefined", why is that?

function instate(loc)
{
    var a;
    var geocoder = new google.maps.Geocoder;
    var infowindow = new google.maps.InfoWindow
    geocoder.geocode({'location': loc}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(5);
            var arrAddress = results[0].address_components;
            $.each(arrAddress, function (i, address_component) {
              if (address_component.types[0] == "administrative_area_level_1"){
              a =  address_component.short_name;

              }     
              //return false; // break the loop   
            });        
          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
    });
    console.log(a);
}
Dean Lin
  • 1
  • 2
  • 1
    http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323 – Teemu Oct 17 '15 at 07:02

1 Answers1

1

Let me clarify what happens in your code. Inside your instate function, you define a variable called a and then call geocode, passing a function as its second parameter. Inside that function you assign a value to a. However, the function has not been called yet just after you defined it. There is a difference between defining a function and calling it. Since the function is asynchronous, it is a sure bet that console.log-ing a value assigned in the function will not behave as you intended it to behave.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • google.maps.event.addListener(markers[i], 'dragend', function(evt){ positionafter = {lat: parseFloat(evt.latLng.lat()), lng: parseFloat(evt.latLng.lng())}; instate(positionafter); }); I call it in other place just like my code above, but those two version of codes do not behave the same.... – Dean Lin Oct 17 '15 at 07:35
  • You call instate, but inside instate, you have the behavior I described in my answer. Once you defined an asynchronous function, it will be executed as a callback. This means that a few milliseconds will pass before it is executed. However, you try to see the value of a before those milliseconds were passed. You might want to console.log(new Date()) inside the function and after the function. You will see that the date outside the function is bigger than the date inside the function. – Lajos Arpad Oct 17 '15 at 07:38
  • Well...I still have some problems...Is there any thing like .done/.fail so that I can use in my code? Or how can I fix this.... – Dean Lin Oct 17 '15 at 10:05
  • I'm sorry to bother you...But I found I'm kind of confused by Promise, could you help me fix this? – Dean Lin Oct 17 '15 at 14:11