Skip to content

Instantly share code, notes, and snippets.

@azanebrain
Created December 10, 2017 20:08
Show Gist options
  • Save azanebrain/84bd8ca2283bcffb9dfac6e8783a1783 to your computer and use it in GitHub Desktop.
Save azanebrain/84bd8ca2283bcffb9dfac6e8783a1783 to your computer and use it in GitHub Desktop.
Defers subsequent calls to an endpoint until the original call has resolved
export class LoadAThing {
private loadingTheThing = null
constructor() {}
/**
* Triggers a call to retrieve something only once
* Subsequent calls will be given the existing promise
*/
public loadThingAsync(): Promise<Environment> {
// Only attempts the call if it is not currently loading
if (!this.loadingTheThing) {
console.log('Thing has not yet been loaded')
this.loadingTheThing = this.retrieveTheThingAsync()
}
return this.loadingTheThing
}
/**
* Retrieves a thing from an endpoint
*/
private async retrieveTheThingAsync() {
const mything = await this.httpService.GET('/api/get/the/thing.json')
return mything
}
}
let loadThing = new LoadAThing()
console.log('loading 1...')
loadThing.loadThingAsync()
.then(result => {console.log('Loaded 1') })
console.log('loading 2...')
loadThing.loadThingAsync()
.then(result => {console.log('Loaded 2') })
console.log('loading 3...')
loadThing.loadThingAsync()
.then(result => {console.log('Loaded 3') })
// Result:
// loading 1...
// Thing has not yet been loaded
// loading 2...
// loading 3...
// Loaded 1
// Loaded 2
// Loaded 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment