peterroe ревизій цього gist 1 week ago. До ревизії
1 file changed, 54 insertions
test.ts(файл створено)
| @@ -0,0 +1,54 @@ | |||
| 1 | + | const _cache = {} | |
| 2 | + | const _loading = {} | |
| 3 | + | ||
| 4 | + | async function simulateFetch(url) { | |
| 5 | + | return new Promise((resolve, reject) => { | |
| 6 | + | setTimeout(() => { | |
| 7 | + | resolve(`Response from ${url}`) | |
| 8 | + | }, 1000) // 模拟延迟1秒的请求 | |
| 9 | + | }) | |
| 10 | + | } | |
| 11 | + | ||
| 12 | + | async function fetchWithCache(url) { | |
| 13 | + | if (url in _cache) | |
| 14 | + | return _cache[url] | |
| 15 | + | ||
| 16 | + | if (!_loading[url]) { | |
| 17 | + | _loading[url] = true | |
| 18 | + | const request = simulateFetch(url) | |
| 19 | + | .then((text) => { | |
| 20 | + | _cache[url] = text | |
| 21 | + | delete _loading[url] | |
| 22 | + | return text | |
| 23 | + | }) | |
| 24 | + | _cache[url] = request | |
| 25 | + | } | |
| 26 | + | ||
| 27 | + | return _cache[url] | |
| 28 | + | } | |
| 29 | + | ||
| 30 | + | let requestStatus = 'idle' | |
| 31 | + | ||
| 32 | + | async function getUser(userId) { | |
| 33 | + | requestStatus = 'loading' | |
| 34 | + | ||
| 35 | + | const cachedRequest = _cache[`/user/${userId}`] | |
| 36 | + | ||
| 37 | + | if (cachedRequest) | |
| 38 | + | return await cachedRequest | |
| 39 | + | ||
| 40 | + | const profile = await fetchWithCache(`/user/${userId}`) | |
| 41 | + | requestStatus = 'success' | |
| 42 | + | return profile | |
| 43 | + | } | |
| 44 | + | ||
| 45 | + | // 测试 | |
| 46 | + | getUser('123') | |
| 47 | + | .then((data) => { | |
| 48 | + | console.log(data) // 第一次请求 | |
| 49 | + | }) | |
| 50 | + | ||
| 51 | + | getUser('123') | |
| 52 | + | .then((data) => { | |
| 53 | + | console.log(data) // 第二次请求,应该从缓存中获取 | |
| 54 | + | }) | |
Новіше
Пізніше