javascript - 变量在 Promise 内变得未定义

标签 javascript promise

我正在开发一个 Ionic 3 应用程序,它使用 Ionic Native Google Maps plugin 。 我正在尝试使用node pool使用 Google map 实例创建标记池。

我的问题是,在 createPool 函数的新 Promise 中, this.map 是未定义的,即使它是由 loadMap() 函数创建的。 我读过this awesome post关于 promise ,但我不知道这如何适用于我的情况。如果有人能帮助我,我将非常感激。

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);
  }

最佳答案

new Promise 内部的 this 与加载 map 的外部 this 不同。您可以在 factory 中声明一个成员变量,将其分配给外部 this 或外部映射,并在新的 Promise 中使用它。

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

关于javascript - 变量在 Promise 内变得未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038049/

相关文章:

javascript - 尝试在 Chrome 扩展程序中使用 SignalR 连接到集线器时出错

javascript - 如何让 AngularJS 输出转义 HTML

javascript - Angular 从服务返回 promise 对象。尝试访问值来更改 ng-if 指令

node.js - (mongoose/promises) 你如何检查文档是否是使用 findOneAndUpdate 和 upsert 创建的

javascript - 我如何强制这个 promise 抛出特定的错误?

javascript - Vue拖放中的递归组件&递归嵌套

javascript - 仅在查看时才删除 Google map 标记

javascript - jQuery 插件 .wrap() 和 .wrapAll() 错误

javascript - UnhandledPromiseRejectionWarning 测试 promise 拒绝

angularjs - 将变量传递给循环中的 promise