Skip to content

Instantly share code, notes, and snippets.

@isaaclyman
Created September 6, 2017 18:30
Show Gist options
  • Save isaaclyman/09a9f1ce1795f564cd9cc3ba99944a07 to your computer and use it in GitHub Desktop.
Save isaaclyman/09a9f1ce1795f564cd9cc3ba99944a07 to your computer and use it in GitHub Desktop.
A pattern for promise result access in ES6, allowing decoupled access from multiple modules with a single shared promise. Good for GET APIs.
import { Api } from 'api'
class PromiseAccessSingleton {
public constructor () { this.init() }
private dataPromise: Promise<any>
private init (): void {
this.dataPromise = Api.GetData().then(data => {
// Transform `data` if needed...
return data
})
}
public GetPromise (): Promise<any> {
return this.dataPromise
}
public GetProp (): Promise<any> {
return this.dataPromise.then(data => data.prop)
}
}
export const PromiseAccess = new PromiseAccessSingleton()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment