2017-02-22 46 views
0

嗨,我使用下面的代码。我需要一些方法让脚本在运行initialize()之前等待clickButton()完​​成。或者等到推完成?任何帮助,将不胜感激。谢谢等到'for循环'或'推'完成然后运行功能 - Javascript

$("#getButtonValue").click(clickButton); 
function clickButton() { 
    for(i = 1; i < counter; i++){ 
     var geocoder = new google.maps.Geocoder(); 
     var address = $('#textbox' + i).val() 
     geocoder.geocode({ 'address': address}, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
         latCoords.push(results[0].geometry.location.lat()); 
         longCoords.push(results[0].geometry.location.lng()); 
      } 
     }); 
    } 
    initialize(); 
} 
+0

Geocoder.geocode是一个承诺? –

+0

我对JavaScript并不熟悉。我只是试图链接两个单独的功能。我需要一个人等待另一个,我不知道如何去做。 – Munnaz

+0

初始化是否被提前调用? –

回答

0

我明白你想要做什么。

如果不使用诺言,一个简单的解决方法是创建一个计数器来查看是否所有的geocoder.geocode()调用都已完成。

$("#getButtonValue").click(clickButton); 
function clickButton() { 
    // A counter variable 
    int completeCount = 0; 
    for(i = 1; i < counter; i++){ 
     var geocoder = new google.maps.Geocoder(); 
     var address = $('#textbox' + i).val() 
     geocoder.geocode({ 'address': address}, function (results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       latCoords.push(results[0].geometry.location.lat()); 
       longCoords.push(results[0].geometry.location.lng()); 

       // Increment completeCount 
       completeCount++; 

       // If all geocoder.geocode() calls received an "OK", initialize() 
       if (completeCount == counter) { 
        initialize(); 
       } 
      } 
     }); 
    } 
} 
+0

干杯队友它的工作完美。我刚刚开始使用JavaScript,它让我感到有些迷惑,它使用的方式 – Munnaz

+0

@ user2441222真的推荐你阅读这个https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript –

+0

@ user2441222一旦你理解了JavaScript中的事件循环,一切都将变得更有意义。 – subwaymatch