Skip to content

Instantly share code, notes, and snippets.

@huang-x-h
Last active March 29, 2018 02:21
Show Gist options
  • Save huang-x-h/144d6716ed38a8b180fde0958d7b9934 to your computer and use it in GitHub Desktop.
Save huang-x-h/144d6716ed38a8b180fde0958d7b9934 to your computer and use it in GitHub Desktop.
Memoize an async function by storing its results
function defaultHasher() {
return JSON.stringify(arguments);
}
function asyncMemoize(fn, hasher=defaultHasher) {
async function memozie() {
let cache = memozie.cache;
const key = hasher(arguments);
if (!cache.hasOwnProperty(key)) {
cache[key] = await fn.apply(this, arguments);
}
return cache[key];
}
memozie.cache = {};
return memozie;
}
// test
function fetch(data) {
return new Promise((resolve) => {
setTimeout(function () {
resolve(data)
}, 1000)
})
}
const fetchMemoize = asyncMemoize(fetch);
const now = Date.now();
fetchMemoize('user').then(function() {
console.log(`fetch user cost time ${Date.now() - now}`);
let current = Date.now();
fetchMemoize('user').then(function() {
console.log(`fetch user cost time ${Date.now() - current}`);
})
})
fetchMemoize('role').then(function() {
console.log(`fetch role cost time ${Date.now() - now}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment