Last active
May 24, 2017 00:44
-
-
Save jtrein/d891dd4e59f229e272344e39f038f420 to your computer and use it in GitHub Desktop.
Cached Fetch GET Request
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
/** | |
* 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