-
-
Save codeBelt/7a82f11121d6b6104655ff8eee0fe1aa to your computer and use it in GitHub Desktop.
Illustrates loading external JS libraries via promise
This file contains 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; | |
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(); |
This file contains 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 coolMapStuff = await GoogleApiService.getCoolMapStuff(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment