Skip to content

Instantly share code, notes, and snippets.

@francisrstokes
Created April 18, 2018 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francisrstokes/6715a398d35ca62dcf38092862a5956a to your computer and use it in GitHub Desktop.
Save francisrstokes/6715a398d35ca62dcf38092862a5956a to your computer and use it in GitHub Desktop.
Caching Promises in a 7 line pure function
const promiseCache = (promFn) => {
let cachedPromise = promFn();
return (refreshCache = false) => {
if (refreshCache) cachedPromise = promFn();
return cachedPromise;
}
}
// Pass a function that generates a promise instead of the promise, so it can be refreshed
const cachedPromise = promiseCache(() => Promise.resolve(Math.random()));
cachedPromise().then(console.log); // 0.3297345352324234
setTimeout(() => cachedPromise().then(console.log), 1000); // 0.3297345352324234
setTimeout(() => cachedPromise(true).then(console.log), 2000); // 0.7619858094911067
setTimeout(() => cachedPromise().then(console.log), 3000); // 0.7619858094911067
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment