使函数在javascript中等待结果

使函数在javascript中等待结果,javascript,google-maps,vue.js,Javascript,Google Maps,Vue.js,我正在使用基于谷歌地图API的Vue(2.x版)构建一个组件 在这个API中,有一个获取映射边界的嵌入函数:getBounds()() 在我的代码中,我用border对象等于0初始化贴图: currentBorders: { b: { b: 0, f: 0, }, f: { b: 0,

我正在使用基于谷歌地图API的Vue(2.x版)构建一个组件

在这个API中,有一个获取映射边界的嵌入函数:getBounds()()

在我的代码中,我用border对象等于0初始化贴图:

          currentBorders: {
              b: {
                  b: 0,
                  f: 0,
              },
              f: {
                  b: 0,
                  f: 0,
              },
          },
之后,我将显示具有某个中心的贴图,并执行getBounds()函数以获取贴图居中后的当前值:

      getBorders() {
          console.log(this.currentBorders); // -> prints the object with all values equal to 0

          this.currentBorders = this.$map.getBounds();

          console.log(this.currentBorders); // -> prints undefined

          return {
              llc_lat: this.currentBorders.f.b,
              llc_lng: this.currentBorders.b.b,
              urc_lat: this.currentBorders.f.f,
              urc_lng: this.currentBorders.b.f,
          };
      },
现在的问题是,在第一次执行期间,我将currentBorders设置为0,但getBounds()的第一次执行返回undefined,这可能是因为映射尚未加载

我想做的是阻止代码的执行,直到getBounds返回有意义的内容。这是路吗?我怎样才能做到这一点

编辑: 这是我通过延迟准备初始化映射的方式:

  deferredReady() {
      this.$map.setOptions({
          styles: mapStyles(),
      });

      this.initializeMapOverlay();
      this.canvasContext = this.mapCanvas.getContext("2d");
      this.$map.addListener("idle", this.idleHandler);
      this.$map.addListener("zoom_changed", () => {
          this.resizeCanvas();
          this.clearCanvas();
      });
      this.$map.addListener("mousemove", this.mouseoverHandler);
      this.$map.addListener("drag", this.fetchHexagons());
  },

您可能应该等待执行代码,直到知道映射已完全加载。我们可以这样做:

google.maps.event.addListenerOnce(map, 'idle', function(){
    // idle state is triggered once map is fully loaded, or failed to load. 
});
通过这种方式,您可以保证只有当映射完全加载并且所有相应的对象都可访问时,代码才会运行。只需将代码放在事件侦听器的主体中

看看这是否对你有用

编辑


我看到您的代码中确实定义了idle事件。我不确定vue是如何工作的,但也许有一种方法可以在运行该事件后运行代码。也许可以将代码放在您的
idleHandler
函数中,看看它是否在那里工作。

您能否向我们展示有关映射实例化的代码以及您的
getBounrds()
调用?为什么不等到映射初始化之后再调用
getBounds
?还是你的问题?