Skip to content

Instantly share code, notes, and snippets.

@element6
Created March 10, 2018 05:42
Show Gist options
  • Save element6/3c9168b1869c8cde7a6f5a48bf308e9d to your computer and use it in GitHub Desktop.
Save element6/3c9168b1869c8cde7a6f5a48bf308e9d to your computer and use it in GitHub Desktop.
memorize promise
// 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