有没有一种方法可以创建在加载 Google 地图 Javascript API 时解析的承诺?

Is there a way to create promise that resolves when Google Maps Javascript API is loaded?

Google 地图 Javascript API 应该加载 this way:

<script>
  function initMap() {
    console.log('loaded');
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></script>

如果我必须回答我的问题,我会这样做:

var googleAPILoadedPromise = Promise.pending();
function initMap() {
  googleAPILoadedPromise.resolve();
}
googleAPILoadedPromise.promise.then(function() {
  console.log('loaded');
});

但是延迟已被弃用并且可能被视为反模式,至少在 bluebird 中是这样。有没有更好的方法?

大概是这样的:

<script>
  var loadGoogleMaps = (function(root, d, x, cb){
    var s = d.createElement(x)
    var a = d.getElementsByTagName(x)[0]
    var cleanup = function (done) {
      return function (value) {
        s.remove()
        delete root[cb]
        return done(value)
      }
    }
    return new Promise(function (resolve, reject){
      root[cb] = cleanup(resolve)
      s.onerror = cleanup(reject)
      s.async = true
      s.src = 'https://maps.googleapis.com/maps/api/js?callback=' + cb
      a.parentNode.insertBefore(s,a)
    });
  })(this, document, 'script', 'googleMapsCallback' + Date.now())
  loadGoogleMaps.then(function(){
    console.log('loaded')
  })
</script>

再想想,我会这样做:

<script>
  var resolvePromise = null;
  var promise = new Promise(function(resolve, reject) {
    resolvePromise = resolve;
  });
  promise.then(function() {
    console.log('loaded');
  });
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=resolvePromise" async defer></script>

打字稿解决方案。删除等待 js 加载的 async 和 defer。

输入index.html

<script src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

使函数成为全局函数,在项目中的任何地方引用。

export function initMap(callback): Promise<any> {
   return new Promise(function(resolve, reject) {
      // SEE IF IN WINDOW OBJECT
      callback(resolve);
   });
}

要引用全局文件,请按照以下步骤操作。

import { initMap } from 'path to initMap';

initMap().then((res) => {
  console.log('map: ' + res);
});