简体   繁体   中英

Javascript function calling after the executing function finishes

I am working on google Maps API. I dont know why the below function is being called after the index++. As far as I know ReverseGeocode() should be called first. Instead of that it is first incrementing and then calling the function which is creating problems for me. The alert boxes are shown as they are written but the middle function is called after the last line of the function is executed ie (index++).

      function placeMarker(location)
      {
          alert("iiii");
          ReverseGeocode(location.lat(),location.lng());
          alert("jjjk");
          index++;
      }

Here is my ReverseGeoCode

  function ReverseGeocode(lat,lng) {     
     var latlng = new google.maps.LatLng(lat, lng);
     geocoder.geocode({'latLng': latlng}, function(results, status)
  {
      if (status == google.maps.GeocoderStatus.OK) 
     {
           if (results[1])
      {

          places[index]=results[0].formatted_address;
          alert(places[index]+"index="+index);
          AddRow('table',results[0].formatted_address);
          document.getElementById("dataa").innerHTML+=results[0].formatted_address+"<br/>";
      }
  }
  else 
  {
    alert("Geocoder failed due to: " + status);
      }
    });
  }

Please Explain. Thanks in advance.

The alert is inside your callback function, which will execute when geocoder.geocode finishes its calculation.

geocoder.geocode appears to asynchronous. Usually, this means geocoder.geocode will start plodding along with its work somewhere else, while your program continues to its local conclusion. When geocoder.geocode later finishes, it will execute your supplied callback function.

I think that the geocoder.geocode is asynchronous. It is executing your anonymous function somethime later, when the value of index has incremented.

function placeMarker(location)
 {
 alert("iiii")
 ReverseGeocode(location.lat(),location.lng(),index);
 alert("jjjk");
 index++;

}

function ReverseGeocode(lat,lng,index) {     
     var latlng = new google.maps.LatLng(lat, lng);
     geocoder.geocode({'latLng': latlng}, function(results, status)
  {
      if (status == google.maps.GeocoderStatus.OK) 
     {
           if (results[1])
      {

          places[index]=results[0].formatted_address;
          alert(places[index]+"index="+index);
          AddRow('table',results[0].formatted_address);
          document.getElementById("dataa").innerHTML+=results[0].formatted_address+"<br/>";
      }
  }
  else 
  {
    alert("Geocoder failed due to: " + status);
      }
    });
  }

In this case, index goes into the local scope of the anonymous function, so it is not overwritten.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM