gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:08:47 24 4
gpt4 key购买 nike

我正在开发一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com