Created
December 19, 2023 20:49
-
-
Save dmitry-tuzenkov/851411bad31243199d79f1d3609fc5c5 to your computer and use it in GitHub Desktop.
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
interface User { | |
id: number; | |
} | |
const storageCache = new Map<number, Promise<User>>(); | |
function fetchUser(id: number): Promise<User> { | |
console.log('id', id) | |
return new Promise((res) => { | |
setTimeout(() => res({ id }), 2000); | |
}); | |
} | |
function fetchUserCached(id: number): Promise<User> { | |
if (!storageCache.has(id)) { | |
try { | |
const user = fetchUser(id); | |
storageCache.set(id, user); | |
} catch (e) { | |
throw e; | |
} | |
} | |
return storageCache.get(id)!; | |
} | |
fetchUserCached(1); | |
fetchUserCached(1); | |
fetchUserCached(1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment