2017-02-22 50 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