Last active
March 29, 2018 02:21
-
-
Save huang-x-h/144d6716ed38a8b180fde0958d7b9934 to your computer and use it in GitHub Desktop.
Memoize an async function by storing its results
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
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; | |
} |
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
// 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