您的位置:首页 > 房产 > 建筑 > 北京平台网站建设找哪家_大连建网站_太原首页推广_营销运营主要做什么

北京平台网站建设找哪家_大连建网站_太原首页推广_营销运营主要做什么

2025/2/26 6:52:28 来源:https://blog.csdn.net/weixin_45042868/article/details/145678930  浏览:    关键词:北京平台网站建设找哪家_大连建网站_太原首页推广_营销运营主要做什么
北京平台网站建设找哪家_大连建网站_太原首页推广_营销运营主要做什么

简单的接口缓存机制,避免了重复请求,同时支持缓存过期时间。

const CACHE_LIFETIME = 30interface ApiCacheOptions {/** 缓存时长(秒) */cacheLifetime?: number
}type CacheStatus = 'notStarted' | 'loading' | 'finished' | 'error'interface CacheItem<T = any> {status: CacheStatusresult: T | nullrequestList: ((res: T | Error) => void)[]timer?: NodeJS.Timeout
}const resultCache = new Map<string, CacheItem>()export async function apiCache<T>(apiKey: string,func: () => Promise<T>,options?: ApiCacheOptions
): Promise<T> {const cacheLifetime = options?.cacheLifetime ?? CACHE_LIFETIMEconst item = getItem<T>(apiKey)if (item.status === 'finished') {return item.result as T}if (item.status === 'loading') {return new Promise<T>((resolve, reject) => {addSubscriber(apiKey, (res) => {if (res instanceof Error) reject(res)else resolve(res)})})}try {item.status = 'loading'item.result = await func()item.status = 'finished'// 设置缓存过期item.timer = setTimeout(() => {removeItem(apiKey)}, cacheLifetime * 1000)onAccessTokenFetched(apiKey, item.result)return item.result} catch (error) {item.status = 'error'onAccessTokenFetched(apiKey, error as Error) // 传递错误给订阅者throw error}
}function getItem<T>(key: string): CacheItem<T> {if (!resultCache.has(key)) {resultCache.set(key, { status: 'notStarted', result: null, requestList: [] })}return resultCache.get(key) as CacheItem<T>
}function removeItem(key: string) {if (resultCache.has(key)) {const item = resultCache.get(key)if (item?.timer) clearTimeout(item.timer) // 清理定时器resultCache.delete(key) // 彻底删除,防止内存泄漏}
}function addSubscriber<T>(key: string, callback: (res: T | Error) => void) {const item = getItem<T>(key)item.requestList.push(callback)
}function onAccessTokenFetched<T>(key: string, result: T | Error) {const item = getItem<T>(key)item.requestList.forEach((callback) => callback(result))item.requestList = [] // 清空请求列表
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com