单例模式中缓存 promise 的核心是共享同一 promise 实例,用 map 以参数为 key 缓存 promise,避免重复请求;需注意 rejected promise 默认也被缓存,可改为仅缓存成功结果或结合超时与兜底策略。

在单例模式中缓存 Promise 对象,核心是「共享同一个 Promise 实例」,避免对相同参数的请求多次发起。关键不是缓存结果值,而是缓存正在执行或已 settled 的 Promise 本身。
用 Map 缓存 Promise(推荐)
以请求参数为 key,Promise 实例为 value,确保相同参数只触发一次 fetch:
class ApiClient {
constructor() {
this.cache = new Map();
}
<p>// 单例实例
static getInstance() {
if (!this.instance) {
this.instance = new ApiClient();
}
return this.instance;
}</p><p>// 获取用户信息(带缓存)
getUser(id) {
const key = <code>user:${id}</code>;</p><pre class="brush:php;toolbar:false;">// 命中缓存:直接返回已存在的 Promise
if (this.cache.has(key)) {
return this.cache.get(key);
}
// 未命中:发起请求,并把 Promise 存入缓存
const promise = fetch(`/api/users/${id}`)
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.finally(() => {
// 可选:请求结束后清除缓存(如需支持更新)
// this.cache.delete(key);
});
this.cache.set(key, promise);
return promise;} }
✅ 优势:天然支持多参数、自动去重、无竞态问题;❌ 注意:缓存的是 Promise 实例,不是数据,所以后续 .then() 都会收到相同响应(包括成功或失败状态)。
缓存后如何刷新或失效?
Promise 一旦 settled 就不可变,所以“刷新”本质是重新生成新 Promise 并覆盖缓存:
- 调用前手动清除:
api.cache.delete('user:123') - 封装
refreshUser(id)方法,内部先删缓存再调用getUser(id) - 对时效敏感的数据(如 token),可在 Promise resolve 后加定时器自动清理:
setTimeout(() => this.cache.delete(key), 5 * 60 * 1000)
更健壮的写法:避免 rejected Promise 永久缓存
如果某次请求失败(如 404),默认会把 rejected Promise 缓存下来,后续调用都立刻 reject——这通常不符合预期。可改用「缓存 resolve 结果,不缓存 reject」:
getUser(id) {
const key = `user:${id}`;
if (this.cache.has(key)) return Promise.resolve(this.cache.get(key));
<p>const promise = fetch(<code>/api/users/${id}</code>)
.then(res => {
if (!res.ok) throw new Error(<code>HTTP ${res.status}</code>);
return res.json();
})
.then(data => {
this.cache.set(key, data); // 只缓存成功数据
return data;
});</p><p>return promise;
}</p>
⚠️ 注意:这样每次失败都会重试(因为没缓存 reject),适合错误需重试的场景;若要“失败也缓存一段时间”,可用 Promise.race([promise, timeout(5000)]) + 自定义错误兜底。
替代方案:用 WeakMap 或全局对象(简单场景)
如果单例只用于前端轻量 API,也可跳过 class,直接用闭包 + 模块级缓存:
// api.js
const cache = new Map();
<p>export function getUser(id) {
const key = <code>user:${id}</code>;
if (cache.has(key)) return cache.get(key);</p><p>const p = fetch(<code>/api/users/${id}</code>).then(r => r.json());
cache.set(key, p);
return p;
}</p>
模块导入即单例,简洁且天然隔离作用域。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











