在执行函数完成后调用 Javascript 函数

Javascript function calling after the executing function finishes

本文关键字:函数 调用 Javascript 执行      更新时间:2023-09-26

我正在研究谷歌地图API。 我不知道为什么在索引++之后调用下面的函数。据我所知,应该首先调用ReverseGeocode()。 取而代之的是,它首先递增然后调用给我带来问题的函数。 警报框在编写时显示,但在执行函数的最后一行(即 (index++))后调用中间函数。

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

这是我的反向地理代码

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

请解释一下。提前谢谢。

警报位于回调函数中,该函数将在geocoder.geocode完成计算时执行。

geocoder.geocode似乎是异步的。 通常,这意味着geocoder.geocode将开始在其他地方进行工作,而您的程序将继续其本地结论。 稍后geocoder.geocode完成后,它将执行您提供的回调函数。

我认为geocoder.geocode是异步的。它会在稍后执行您的匿名函数,当index的值增加时。

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

在这种情况下,index进入匿名函数的本地范围,因此不会被覆盖。