Skip to content

Instantly share code, notes, and snippets.

@jtrein
Last active May 24, 2017 00:44
Show Gist options
  • Save jtrein/d891dd4e59f229e272344e39f038f420 to your computer and use it in GitHub Desktop.
Save jtrein/d891dd4e59f229e272344e39f038f420 to your computer and use it in GitHub Desktop.
Cached Fetch GET Request
/**
* CachedCall
*
* Caches a network GET request. When called more than once, the closure returns the cached value.
*
* @param {func} asyncFunc - i.e. `async (arg) => {}`
* @param ...args - spreads arguments into an array
* @return {Promise} cachedResponse | unresolvedCall - thenable with a resolved value
*/
export const CachedCall = (asyncFunc, ...args) => {
let cachedResponse;
let callCount;
let resolver;
let unresolvedCall;
return async () => {
callCount = callCount ? callCount += 1 : 1;
if (!cachedResponse && callCount === 1) {
unresolvedCall = new Promise(resolve => (resolver = resolve));
const res = await fetch(asyncFunc(...args));
cachedResponse = await res.json();
resolver(cachedResponse);
return cachedResponse;
}
return unresolvedCall;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment