【问题标题】:Wait until 'for loop' or 'push' is complete then run function - Javascript等到'for loop'或'push'完成然后运行函数 - Javascript
【发布时间】:2017-02-22 23:35:15
【问题描述】:

您好,我正在使用以下代码。我需要一些方法让脚本等到 clickButton() 完成后再运行 initialize()。或者也许等到推送完成?任何帮助,将不胜感激。谢谢

 $("#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();
 }

【问题讨论】:

  • Geocoder.geocode 是一个承诺?
  • 我对javascript不太熟悉。我只是想链接两个单独的功能。我需要一个等待另一个,但不知道该怎么做。
  • 是否提前调用了初始化?

标签: javascript loops for-loop push


【解决方案1】:

我明白你在做什么。

如果不使用 promise,一个简单的解决方法是创建一个计数器来查看所有 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();
                }
            } 
        }); 
    }
}

【讨论】:

  • 干杯,它工作完美。我刚开始使用 javascript,它的方式让我有点困惑
  • @user2441222 真的推荐你阅读这个pluralsight.com/guides/front-end-javascript/…
  • @user2441222 一旦你理解了 javascript 中的事件循环,一切都会变得更有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 2020-11-12
相关资源
最近更新 更多