Last active
March 31, 2017 22:43
-
-
Save vbravest/517495ddc040bf0c2dce6dd64d7129d4 to your computer and use it in GitHub Desktop.
Illustrates loading external JS libraries via promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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