🧠 一、限制并发请求数量
. 请求队列 / 并发池
使用并发控制技术,如「请求池」或「信号量」控制并发请求数量,防止前端同时发出大量请求。
// 并发控制器示例
class RequestPool {
private poolSize: number;
private queue: (() => Promise<void>)[] = [];
private activeCount = 0;
constructor(poolSize: number) {
this.poolSize = poolSize;
}
async add(task: () => Promise<void>) {
if (this.activeCount < this.poolSize) {
this.activeCount++;
await task();
this.activeCount--;
this.runNext();
} else {
this.queue.push(task);
}
}
private runNext() {
const next = this.queue.shift();
if (next) this.add(next);
}
}
🔁 二、合并请求(请求合并 / 批处理)
1. 多次请求合并为一次(如搜索框实时搜索)
比如用户在搜索时快速输入,可以防抖(见下),然后将多个请求合并为一个。
ts
复制编辑
// 利用 lodash 的 debounce(防抖)
import debounce from 'lodash.debounce';
const fetchSuggestions = debounce((keyword) => {
fetch(`/api/search?q=${keyword}`);
}, 300);
🔄 三、缓存策略(减少重复请求)
1. 缓存已请求过的数据
对于不频繁变化的数据,利用前端缓存(如 Map、localStorage、IndexedDB)避免重复请求。
const cache = new Map();
async function fetchData(id: string) {
if (cache.has(id)) {
return cache.get(id);
}
const res = await fetch(`/api/data/${id}`);
const data = await res.json();
cache.set(id, data);
return data;
}
⏱ 四、节流 / 防抖(输入类、滚动类操作)
1. 防抖(debounce):延迟请求直到用户输入停止
适用于搜索、表单输入等场景。
2. 节流(throttle):固定频率发送请求
适用于滚动加载、窗口 resize 事件等。
🔐 五、避免重复点击
1. 按钮点击时禁用,防止重复请求
ts
复制编辑
const handleClick = async () => {
if (loading) return;
setLoading(true);
await fetch('/api/action');
setLoading(false);
};