Created
August 24, 2018 13:40
-
-
Save emmiep/95d12ad12631b8467647e52aec74c29f to your computer and use it in GitHub Desktop.
Async caching with WeakMap and promises
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
| export function createAsyncCache(fn) { | |
| const cache = new WeakMap(); | |
| return { | |
| get(key) { | |
| if (cache.has(key)) { | |
| return cache.get(key); | |
| } | |
| const promise = Promise.resolve(fn(key)); | |
| cache.set(key, promise); | |
| return promise; | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment