Skip to content

Instantly share code, notes, and snippets.

@kbravest
Last active March 31, 2017 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kbravest/517495ddc040bf0c2dce6dd64d7129d4 to your computer and use it in GitHub Desktop.
Save kbravest/517495ddc040bf0c2dce6dd64d7129d4 to your computer and use it in GitHub Desktop.
Illustrates loading external JS libraries via promise
/**
* Illustrates loading external JS libraries via promise
*/
class GoogleApiService {
static promise = null;
baseUrl = '';
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
async getCoolMapStuff() {
const google = await this.getApi();
return google.getCoolMapStuff();
// Guaranteed it will always work!!!!!
}
async getApi() {
if (GoogleApiService.promise == null) {
GoogleApiService.promise = new Promise(resolve => {
window.googleApiCallback = () => {
// window.google is available!!
resolve(window.google);
};
const url = this.baseUrl + '?callback=googleApiCallback';
this.appendScript(url);
});
}
return GoogleApiService.promise;
}
appendScript(url) {
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.setAttribute('src', url);
document.head.appendChild(script);
}
}
export default GoogleApiService;
const baseUrl = 'https://maps.googleapis.com/maps/api/js';
const googleApiService = new GoogleApiService(baseUrl);
const coolMapStuff = await googleApiService.getCoolMapStuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment