Created
October 21, 2019 22:32
-
-
Save andrewmacheret/6ca5ffbffe43e8490bc80fb94046bfd0 to your computer and use it in GitHub Desktop.
cache of an async function
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 resultMap: Map<string, any> = new Map(); | |
| const loadData = async (loader: Function, ...args: any) => { | |
| // is there a better way... | |
| const key = JSON.stringify(args); | |
| if (resultMap.has(key)) { | |
| const val = resultMap.get(key); | |
| if (val.state === 'loading') { | |
| return await val.promise(); | |
| } else if (val.state === 'failed') { | |
| throw val.error; | |
| } else { | |
| return val.result; | |
| } | |
| } | |
| const resolves: Function[] = []; | |
| const rejects: Function[] = []; | |
| const promise = () => { | |
| return new Promise((resolve, reject) => { | |
| resolves.push(resolve); | |
| rejects.push(resolve); | |
| }); | |
| } | |
| resultMap.set(key, {state: 'loading', promise}); | |
| try { | |
| const result = await loader(...args); | |
| resultMap.set(key, {state: 'loaded', result}); | |
| resolves.forEach(resolve => resolve(result)); | |
| return result; | |
| } catch(error) { | |
| resultMap.set(key, {state: 'failed', error}); | |
| rejects.forEach(reject => reject(error)); | |
| throw error; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment