test.ts
· 1.0 KiB · TypeScript
Raw
const _cache = {}
const _loading = {}
async function simulateFetch(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(`Response from ${url}`)
}, 1000) // 模拟延迟1秒的请求
})
}
async function fetchWithCache(url) {
if (url in _cache)
return _cache[url]
if (!_loading[url]) {
_loading[url] = true
const request = simulateFetch(url)
.then((text) => {
_cache[url] = text
delete _loading[url]
return text
})
_cache[url] = request
}
return _cache[url]
}
let requestStatus = 'idle'
async function getUser(userId) {
requestStatus = 'loading'
const cachedRequest = _cache[`/user/${userId}`]
if (cachedRequest)
return await cachedRequest
const profile = await fetchWithCache(`/user/${userId}`)
requestStatus = 'success'
return profile
}
// 测试
getUser('123')
.then((data) => {
console.log(data) // 第一次请求
})
getUser('123')
.then((data) => {
console.log(data) // 第二次请求,应该从缓存中获取
})
| 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 | }) |
| 55 |