Created
April 18, 2018 09:09
-
-
Save francisrstokes/6715a398d35ca62dcf38092862a5956a to your computer and use it in GitHub Desktop.
Caching Promises in a 7 line pure function
This file contains 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
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