通过请求队列控制并发数,使用PriorityQueue实现优先级调度,结合AbortController处理过期请求,可构建高效请求管理器。

在现代前端开发中,频繁的网络请求可能导致性能问题或服务端压力过大。合理地进行 请求优先级调度 和 并发控制 能有效提升用户体验和系统稳定性。JavaScript 提供了多种方式来实现这些策略,结合 Promise、async/await 和队列机制即可构建可控的请求管理器。
限制同时发送的请求数量是并发控制的核心。可以通过维护一个任务队列,动态控制执行中的请求数量,避免资源耗尽。
以下是一个简单的并发控制器示例:
class RequestPool {
constructor(maxConcurrent = 3) {
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [];
}
add(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({
fn: requestFn,
resolve,
reject
});
this._dequeue();
});
}
async _dequeue() {
if (this.running >= this.maxConcurrent || this.queue.length === 0) return;
const task = this.queue.shift();
this.running++;
try {
const result = await task.fn();
task.resolve(result);
} catch (error) {
task.reject(error);
} finally {
this.running--;
this._dequeue();
}
}
}
使用方式:
立即学习“Java免费学习笔记(深入)”;
const pool = new RequestPool(2);
pool.add(() => fetch('/api/user/1').then(res => res.json()))
.then(data => console.log(data));
pool.add(() => fetch('/api/user/2').then(res => res.json()));
某些请求(如用户交互触发的)应优先于后台同步任务。可在队列中为任务添加优先级字段,高优先级任务排在前面。
修改队列的入队逻辑,按优先级排序:
class PriorityQueue {
constructor(maxConcurrent = 3) {
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [];
}
add(requestFn, priority = 0) {
return new Promise((resolve, reject) => {
// 插入时按优先级降序排列(数值越大越优先)
const task = { fn: requestFn, resolve, reject, priority };
let inserted = false;
for (let i = 0; i < this.queue.length; i++) {
if (task.priority > this.queue[i].priority) {
this.queue.splice(i, 0, task);
inserted = true;
break;
}
}
if (!inserted) {
this.queue.push(task);
}
this._dequeue();
});
}
async _dequeue() {
if (this.running >= this.maxConcurrent || this.queue.length === 0) return;
const task = this.queue.shift();
this.running++;
try {
const result = await task.fn();
task.resolve(result);
} catch (error) {
task.reject(error);
} finally {
this.running--;
this._dequeue();
}
}
}
调用时指定优先级:
const queue = new PriorityQueue(2);
// 高优先级:用户点击加载数据
queue.add(() => fetch('/api/profile').then(r => r.json()), 10);
// 低优先级:页面初始化批量拉取
queue.add(() => fetch('/api/logs').then(r => r.json()), 1);
当高优先级请求频繁触发时(如搜索输入),旧请求可能已无意义。可通过 AbortController 主动取消。
扩展请求函数支持中断:
function createCancelableRequest(url) {
const controller = new AbortController();
const promise = fetch(url, { signal: controller.signal }).then(r => r.json());
return { promise, cancel: () => controller.abort() };
}
// 在队列中管理可取消任务(适用于防抖场景)
在真实项目中,可以封装一个统一的 requestManager,集成并发控制、优先级、缓存、重试等功能。例如:
以上就是怎样使用JavaScript进行网络请求的优先级调度与并发控制?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号