js实现单请求
实现单请求的 JavaScript 方法
在 JavaScript 中实现单请求通常指确保某个操作(如数据加载或提交)仅执行一次,避免重复请求。以下是几种常见场景的实现方式:
使用标志位控制请求
通过布尔变量标记请求状态,防止重复触发:
let isRequesting = false;
function fetchData() {
if (isRequesting) return;
isRequesting = true;
fetch('https://api.example.com/data')
.then(response => response.json())
.finally(() => {
isRequesting = false;
});
}
基于 Promise 的缓存
对异步请求结果进行缓存,后续调用直接返回缓存的 Promise:

let requestPromise = null;
function getData() {
if (!requestPromise) {
requestPromise = fetch('https://api.example.com/data')
.then(response => response.json());
}
return requestPromise;
}
防抖(Debounce)技术
短时间内多次调用时,仅执行最后一次请求:
function debounce(func, delay) {
let timeoutId;
return function() {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, arguments), delay);
};
}
const fetchData = debounce(() => {
fetch('https://api.example.com/data');
}, 500);
AbortController 取消重复请求
利用 AbortController 中止之前的未完成请求:

let controller = null;
function fetchData() {
if (controller) controller.abort();
controller = new AbortController();
fetch('https://api.example.com/data', {
signal: controller.signal
}).catch(err => {
if (err.name !== 'AbortError') throw err;
});
}
单例模式封装
将请求逻辑封装为单例,确保全局唯一实例:
class ApiService {
constructor() {
if (!ApiService.instance) {
ApiService.instance = this;
}
return ApiService.instance;
}
fetchData() {
return fetch('https://api.example.com/data');
}
}
const api = new ApiService();
api.fetchData();
根据具体需求选择合适的方法:
- 简单场景可用标志位或 Promise 缓存
- 用户频繁操作时建议防抖或 AbortController
- 需要全局控制时考虑单例模式






