Skip to content

Instantly share code, notes, and snippets.

@emmiep
Created August 24, 2018 13:40
Show Gist options
  • Select an option

  • Save emmiep/95d12ad12631b8467647e52aec74c29f to your computer and use it in GitHub Desktop.

Select an option

Save emmiep/95d12ad12631b8467647e52aec74c29f to your computer and use it in GitHub Desktop.
Async caching with WeakMap and promises
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