Last active 1 week ago

test.ts Raw
1const _cache = {}
2const _loading = {}
3
4async function simulateFetch(url) {
5 return new Promise((resolve, reject) => {
6 setTimeout(() => {
7 resolve(`Response from ${url}`)
8 }, 1000) // 模拟延迟1秒的请求
9 })
10}
11
12async 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
30let requestStatus = 'idle'
31
32async 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// 测试
46getUser('123')
47 .then((data) => {
48 console.log(data) // 第一次请求
49 })
50
51getUser('123')
52 .then((data) => {
53 console.log(data) // 第二次请求,应该从缓存中获取
54 })
55