Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Google Maps Javascript API is supposed to be loaded this way:

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

If I had to answer my question, I'd do it like so:

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

But deferreds are deprecated and possibly considered an anti-pattern, at least in bluebird. Is there any better way?

like image 352
x-yuri Avatar asked Apr 12 '16 13:04

x-yuri


2 Answers

On second thought, I'd do it like this:

<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>
like image 139
x-yuri Avatar answered Sep 30 '22 21:09

x-yuri


Probably like this:

<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>
like image 35
idbehold Avatar answered Sep 30 '22 20:09

idbehold