javascript - 在 forEach 循环中使用 Promise
问题描述
我是新手,Promise
不能完全正确。
我正在尝试创建一种情况,如果页面上的元素需要它,我会加载谷歌地图 API 脚本。这部分我已经开始工作,我正在努力解决的是如果页面上有超过 1 个元素需要谷歌地图 API,我只需要加载一次脚本。
这是我到目前为止所拥有的。
索引.html
<div class="map" id="map-1" data-module="map" style="height: 100vh;"></div>
<div class="map" id="map-2" data-module="map" style="height: 100vh;"></div>
<div class="map" id="map-3" data-module="map" style="height: 100vh;"></div>
<div class="map" id="map-4" data-module="map" style="height: 100vh;"></div>
加载GoogleMapsApi.js
export default class LoadGoogleMapsAPI {
constructor() {
this.apiKey = '********';
// set a globally scoped callback if it doesn't already exist
/* eslint no-underscore-dangle: 0 */
if (!window._GoogleMapsApi) {
this.callbackName = '_GoogleMapsApi.mapLoaded';
window._GoogleMapsApi = this;
window._GoogleMapsApi.mapLoaded = this.mapLoaded.bind(this);
}
}
/**
* Load the Google Maps API javascript
*/
async load() {
if (!this.promise) {
this.promise = await new Promise((resolve) => {
this.resolve = resolve;
if (typeof window.google === 'undefined') {
const script = document.createElement('script');
script.src = `//maps.googleapis.com/maps/api/js?key=${window._GoogleMapsApi.apiKey}&callback=${window._GoogleMapsApi.callbackName}`;
script.async = true;
document.body.append(script);
} else {
this.resolve();
}
});
}
return this.promise;
}
/**
* Globally scoped callback for the map loaded
*/
mapLoaded() {
if (this.resolve) {
this.resolve();
}
}
}
地图.js
import GoogleMapsApi from '../utils/loadGoogleMapsApi';
export default class MapViewModel {
constructor(module) {
this.module = module;
const gmapApi = new GoogleMapsApi();
gmapApi.load().then(() => {
// safe to start using the API now
new google.maps.Map(this.module, {
center: { lat: 51.5074, lng: -0.1278 },
zoom: 11,
});
// etc.
});
}
static init() {
const instances = document.querySelectorAll('[data-module="map"]');
instances.forEach((module) => {
const options = JSON.parse(module.getAttribute('data-map-settings'));
new MapViewModel(module, options);
});
}
}
MapViewModel.init();
问题在于load()
功能(我认为)。我尝试了各种不同的东西,这是我得到的最接近的。似乎代码要么不等待并将脚本标签放入 4 次,要么代码在脚本标签加载之前解析并且我的google.maps.Map(...)
不起作用。
我能得到的任何帮助将不胜感激。
干杯,卢克。
更新
解决了
感谢@jcubic 的新代码帮助我最终找到了解决方案。
加载GoogleMapsApi.js
export default class LoadGoogleMapsAPI {
/**
* Load the Google Maps API javascript
*/
static load() {
this.apiKey = '******';
if (!this.promise) {
this.promise = new Promise((resolve) => {
if (typeof window.google === 'undefined') {
const script = document.createElement('script');
script.onload = resolve;
script.src = `//maps.googleapis.com/maps/api/js?key=${this.apiKey}`;
script.async = true;
document.body.append(script);
}
});
}
return this.promise;
}
}
地图.js
import GoogleMapsApi from '../utils/loadGoogleMapsApi';
export default class MapViewModel {
constructor(module) {
this.module = module;
GoogleMapsApi.load().then(() => {
// safe to start using the API now
new google.maps.Map(this.module, {
center: { lat: 51.5074, lng: -0.1278 },
zoom: 11,
});
// etc.
});
}
static init() {
const instances = document.querySelectorAll('[data-module="map"]');
instances.forEach((module) => {
const options = JSON.parse(module.getAttribute('data-map-settings'));
new MapViewModel(module, options);
});
}
}
MapViewModel.init();
所以解决方案的两个部分是使 loadGoogleMapsApi.js 成为一个静态类并在函数constructor
内移动代码。load()
然后还将load()
函数更改为不使用 async/await 并添加script.onload = resolve
.
解决方案
如果你使用this.promise = await new Promise((resolve) => {
this.promise 将不是一个承诺,而是承诺解决的价值,这就是 async/await 的工作方式。您正在使用未定义(resolve() 没有价值)来解决它,所以this.promise
它是未定义的(它总是错误的)。
编辑你还需要调用 this.resolve 否则如果你在一个循环中调用你在它完成之前多次执行它,你可能还想在脚本准备好时解决承诺:
load() {
if (!this.promise) {
this.promise = new Promise((resolve) => {
if (typeof window.google === 'undefined') {
const script = document.createElement('script');
script.onload = resolve;
script.src = `//maps.googleapis.com/maps/api/js?key=${window._GoogleMapsApi.apiKey}&callback=${window._GoogleMapsApi.callbackName}`;
script.async = true;
document.body.append(script);
}
});
}
return this.promise;
}
推荐阅读
- reactjs - 如何在 react-native 中使用“this.props.navigation.goBack()”将数据传递到另一个屏幕?
- reactjs - react-google-maps “谷歌未定义”
- python - Pandas .dt.round 随机取整最近的小时?
- azure-active-directory - 如何克服 Microsoft Graph 中返回的记录限制?
- clojure - Clojure 循环函数仅返回 Nil
- apache-spark - spark中的作业执行
- python - 为什么 pool.map 不启动新进程?
- django - Django ORM FieldError 查询某些计算
- sql - 如何在sql server中找到重命名表的用户
- node.js - 如何通过 Swagger Cloud Endpoints 传递自签名 JWT