javascript 变量在promise中变为undefined

14ifxucb  于 2023-05-12  发布在  Java
关注(0)|答案(3)|浏览(193)

我正在开发一个使用Ionic Native Google Maps plugin的Ionic 3应用程序。我尝试使用node pool和Google Maps示例来创建标记池。
我的问题是,在createPool函数的新Promise中,this.map是未定义的,即使它是由loadMap()函数创建的。我读了这篇关于承诺的文章,但我不知道它如何适用于我的情况。如果有人能帮助我,我将不胜感激。

ngAfterViewInit() {
    this.platform.ready()
      .then(_ => {
        return this.loadMap()
      })
      .then(_ => {
        this.markerpool = this.createPool();
        this.markerpool.on('factoryCreateError', err => console.log(err));
      })
} 

createPool() {
    var factory = {
      create: function () {
        return new Promise((resolve, reject) => {
          this.map.addMarker({
            icon: 'assets/icon/sun.png',
            visible: false
          })
            .then(marker => {
              // icon anchor set to the center of the icon
              marker.setIconAnchor(42, 37);
              resolve(marker);
            })
        })
      },
      destroy: function (marker: Marker) {
        return new Promise((resolve, reject) => {
          marker.remove();
          resolve();
        })
      }
    }
    var opts = {
      max: 60, // maximum size of the pool
      min: 20 // minimum size of the pool
    }
    return GenericPool.createPool(factory, opts);
  }

loadMap() {
    this.mapElement = document.getElementById('map');
    let mapOptions: GoogleMapOptions = {
      camera: {
        target: {
          lat: 40.9221968,
          lng: 14.7907662
        },
        zoom: maxzoom,
        tilt: 30
      },
      preferences: {
        zoom: {
          minZoom: minzoom,
          maxZoom: maxzoom
        }
      }
    };

    this.map = this.googleMaps.create(this.mapElement, mapOptions);
    this.zoomLevel = this.getZoomLevel(maxzoom);
    return this.map.one(GoogleMapsEvent.MAP_READY);
  }
gtlvzcf8

gtlvzcf81#

new Promise内部的this与加载map的外部this不同。你可以在factory内部声明一个成员变量,它被赋值给外部的this,或者赋值给外部的map,然后在新的Promise中使用它。

var factory = {
    outerthis: this, //or outermap:this.map
    create: ...
       ...
       this.outerthis.map.addMarker(... //or access this.outermap.addMarker directly
taor4pac

taor4pac2#

如果使用箭头函数而不是create: function () {,则值中的this将是调用createPool的对象(具有map属性),而不是factory

tag5nh1u

tag5nh1u3#

尝试将var替换为letlet将的变量范围保持在函数之外。您还需要使用()=>{}而不是function()

let factory = {
  create: () => {
    return new Promise((resolve, reject) => {
      this.map.addMarker({
        icon: 'assets/icon/sun.png',
        visible: false
      })
      .then(marker => {
        // icon anchor set to the center of the icon
        marker.setIconAnchor(42, 37);
        resolve(marker);
      })
    })
  },
  destroy: (marker: Marker) => {
    return new Promise((resolve, reject) => {
      marker.remove();
      resolve();
    })
  }
}
let opts = {
  max: 60, // maximum size of the pool
  min: 20 // minimum size of the pool
}

相关问题