Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Forked from kbravest/library-promise.js
Created March 31, 2017 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeBelt/7a82f11121d6b6104655ff8eee0fe1aa to your computer and use it in GitHub Desktop.
Save codeBelt/7a82f11121d6b6104655ff8eee0fe1aa 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;
async getCoolMapStuff() {
const google = await getApi();
return google.getCoolMapStuff();
// Guaranteed it will always work!!!!!
}
static appendScript(url) {
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.setAttribute('src', url);
document.head.appendChild(script);
}
static async getApi() {
if (GoogleApiService.promise == null) {
GoogleApiService.promise = new Promise(resolve => {
window.googleApiCallback = () => {
// window.google is available!!
resolve(window.google);
};
const url = 'https://maps.googleapis.com/maps/api/js?callback=googleApiCallback';
appendScript(url);
});
}
return GoogleApiService.promise;
}
}
export default new GoogleApiService();
const coolMapStuff = await GoogleApiService.getCoolMapStuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment