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) // 第二次请求,应该从缓存中获取 })