Created
September 6, 2017 18:30
-
-
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.
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
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