Created
March 10, 2018 05:42
-
-
Save element6/3c9168b1869c8cde7a6f5a48bf308e9d to your computer and use it in GitHub Desktop.
memorize promise
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
// assume retry if promise is rejected, with a ttl feature | |
function promiseTest() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
// console.log('promise done') | |
if(Date.now()%2) | |
resolve('ok') | |
else | |
reject('not ok') | |
}, 3000) | |
}) | |
} | |
function memoize(method, ttl=60*60) { | |
let cache = {}, expire = {}; | |
return async function() { | |
let args = JSON.stringify(arguments); | |
if(cache[args] && cache[args].isResolved && Date.now() < expire[args]){ | |
return cache[args] | |
} | |
cache[args] = method.apply(this, arguments); | |
expire[args] = Date.now() + ttl * 1000 | |
cache[args].then(val => { cache[args].isResolved = true; return val}) | |
return cache[args]; | |
}; | |
} | |
a = memoize(async function() { | |
return promiseTest() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment