【问题标题】:how do I execute something after all the callbacks are finished in javascript在javascript中完成所有回调后如何执行某些操作
【发布时间】:2012-02-06 06:57:36
【问题描述】:

我正在使用 google map v3 进行一些地址翻译。 我将请求和回调函数传递给 Geocoder.geocode。回调函数将在地图上添加一个标记。毕竟,我使用map.FitBounds(fullBounds) 让所有制造商都在视线范围内,其中mapMap 对象,fullBoundsLatLngBounds 对象。

下面是我的一段代码:

    for(i = 0; i < requestArray.length; i ++)
    {
        geo.geocode(requestArray[i], calbck);
    }

我的问题是,当我在 calbck 中调用 map.fitBounds(fullBounds) 时,并非所有回调函数都已完成(在我的观察中始终没有完成)。那么如何延迟fitBounds 让所有回调函数都完成呢?

【问题讨论】:

    标签: javascript google-maps google-maps-markers


    【解决方案1】:

    如果您知道回调的数量,您可以在回调中调用其他函数来增加计数器,当计数器与回调的数量相同时,您可以执行代码。

    类似:

    function myFunctionToExecuteAfterCallbacks()
    {
      numCallbacks++;
      if(numCallbacks == numAllCallbacks)
      {
        // Code to execute here...
      }
    }
    

    至少我曾经是这样解决的。不知道有什么更好的解决方案。 也许您可以触发一个事件,而不是调用另一个函数。但是几乎是一样的……

    顺便说一句,我找到了一些关于此的主题:

    Best solution to wait for all ajax callbacks to be executed

    javascript: execute a bunch of asynchronous method with one callback

    【讨论】:

      【解决方案2】:

      如果您使用 Promise,请查看 Promise.all()

      你也可以进行递归回调。

      doStuff() {
        if (requestArray.length) {
          geo.geocode(requestArray.pop(), this.doStuff)
        } else {
          // we're done;
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-13
        • 1970-01-01
        • 2012-02-02
        相关资源
        最近更新 更多