实现异步原子依赖缓存
解读
“异步原子依赖缓存”在国内一线/二线前端面试中通常被拆成两层含义:
- 异步:所有资源(接口、模块、甚至 WebAssembly)通过 Promise/async 返回;
- 原子+依赖:同一时刻对同一 key 只允许一次网络请求(原子),且当 key A 依赖 key B 时,B 的缓存失效要级联触发 A 的重新获取(依赖)。
面试官想听到的是:
- 如何用单例模式锁掉重复请求,避免“缓存击穿”;
- 如何用DAG 拓扑描述并触发依赖失效;
- 如何在前端工程里落地(React/Vue 状态管理、Service Worker、Vite 插件等);
- 如何兼顾内存+IndexedDB 二级缓存、SSR 注水复用、错误重试与竞态取消。
知识点
- Promise 单例锁:用 Map<key, Promise> 保证同一 key 仅一个飞行请求。
- 缓存三要素:key → value + ttl + 依赖列表;失效时递归标记下游。
- 拓扑排序+订阅发布:建立依赖图,失效时按反拓扑序触发回调。
- AbortController:取消过期请求,防止竞态。
- 内存 vs 持久化:内存用 LRU 控制上限,IndexedDB 做离线降级。
- 框架结合:React 中可封装为 useAsyncAtom,Vue3 可用 reactive + effectScope。
- 性能指标:缓存命中率、请求去重率、FCP/TTI 提升。
答案
以下给出可直接在项目中落地的 TypeScript 实现,满足“异步+原子+依赖”三大要求,并附带 React Hook 示例。
// cache.ts
type DepGraph = Map<string, Set<string>>; // 父 → 子
class AsyncAtomCache {
private flying = new Map<string, Promise<any>>(); // 原子锁
private store = new Map<string, { value: any; ttl: number; deps: string[] }>();
private deps: DepGraph = new Map(); // 依赖图
private subscribers = new Map<string, Set<() => void>>(); // 订阅
async get<T>(
key: string,
fetcher: () => Promise<T>,
{ ttl = 60000, deps = [] }: { ttl?: number; deps?: string[] } = {}
): Promise<T> {
// 1. 命中缓存且未过期
const hit = this.store.get(key);
if (hit && Date.now() < hit.ttl) return hit.value;
// 2. 原子锁:同一 key 仅一个飞行请求
if (this.flying.has(key)) return this.flying.get(key);
// 3. 注册依赖关系
deps.forEach(d => {
if (!this.deps.has(d)) this.deps.set(d, new Set());
this.deps.get(d)!.add(key);
});
const promise = fetcher()
.then(res => {
this.store.set(key, { value: res, ttl: Date.now() + ttl, deps });
this.flying.delete(key);
return res;
})
.catch(e => {
this.flying.delete(key);
throw e;
});
this.flying.set(key, promise);
return promise;
}
invalidate(key: string) {
this.store.delete(key);
// 递归失效下游
const children = this.deps.get(key);
if (children) {
children.forEach(k => this.invalidate(k));
}
// 通知订阅者
this.subscribers.get(key)?.forEach(fn => fn());
}
subscribe(key: string, cb: () => void) {
if (!this.subscribers.has(key)) this.subscribers.set(key, new Set());
this.subscribers.get(key)!.add(cb);
return () => this.subscribers.get(key)!.delete(cb);
}
}
export const cache = new AsyncAtomCache();
React Hook 封装(支持 Suspense):
// useAsyncAtom.ts
import { use } from 'react'; // React 18 官方 use
import { cache } from './cache';
export function useAsyncAtom<T>(
key: string,
fetcher: () => Promise<T>,
options?: Parameters<typeof cache.get>[2]
) {
const promise = cache.get(key, fetcher, options);
return use(promise); // 直接挂到 Suspense
}
使用示例:
function UserInfo({ id }: { id: string }) {
const data = useAsyncAtom(
`user-${id}`,
() => fetch(`/api/user/${id}`).then(r => r.json()),
{ ttl: 30000, deps: [`role-${id}`] }
);
return <div>{data.name}</div>;
}
当后台刷新角色接口后,只需调用 cache.invalidate(role-${id}),所有依赖该角色的用户卡片会自动重新取数,且同一卡片在 30 s 内多次渲染不会触发重复请求,实现真正的异步原子依赖缓存。
拓展思考
- SSR 同构:在 Node 端预取数据后,把缓存快照序列化到
window.__ASYNC_ATOM__,浏览器端直接复用,避免二次请求。 - 优先级调度:给 key 加权重,网络慢时优先保留高优缓存,低优请求延后。
- Web Worker 缓存:把 AsyncAtomCache 放到 SharedWorker,实现多 Tab 级共享与原子锁。
- 灰度与实验:在 key 里拼接
abVersion,不同实验组互不污染,同时支持实时切换版本立即失效。 - 可视化调试:在 devtools 增加 panel,展示当前依赖图、命中率、飞行队列,帮助 QA 快速定位“缓存未更新”客诉。