Skip to content

Instantly share code, notes, and snippets.

@mark0978
Last active February 21, 2019 16:29
Show Gist options
  • Save mark0978/2d5dd859de9ae85feee3e6da86ce5fe0 to your computer and use it in GitHub Desktop.
Save mark0978/2d5dd859de9ae85feee3e6da86ce5fe0 to your computer and use it in GitHub Desktop.
A simple promise based cache for Authors
class AuthorCache {
cache = {};
getAuthor(url) {
// Returns a promise for
let result = this.cache[url];
if (result) {
if (result.then) {
// Request is already in flight, just return this promise, we don't need to do anything else
console.debug("Request already in flight for ", url);
return result;
} else {
// We already have the data, wrap it in a resolved promise so the component can't
// tell the difference
let promise = new Promise(function(resolve, reject) {
resolve(result);
});
console.debug("Returning cached copy for ", url);
return promise;
}
} else {
// We don't have the data in the cache, we need to request it.
let promise = fetch(url).then(res => res.json());
console.debug("Fetching ", url);
this.cache[url] = promise;
promise.then(res => {
// Replace the promise in the cache with the actual data we received
this.cache[url] = res;
return res;
});
return promise;
}
}
}
let authorCache = new AuthorCache();
export { authorCache };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment