Promise限流与防抖结合可有效控制异步任务并发。首先通过PromisePool限制同时执行的任务数量,避免服务器压力过大;再利用防抖函数延迟执行,过滤高频触发事件,确保只有最后一次调用生效;两者组合适用于搜索、上传等场景,提升系统稳定性与用户体验。

在处理大量异步任务时,JavaScript中的并发控制至关重要。如果不加以限制,同时发起过多请求可能导致接口限流、服务器压力过大或浏览器卡顿。通过Promise限流和防抖策略,可以有效管理异步任务的执行节奏,提升系统稳定性与用户体验。
限流的核心是控制同一时间运行的Promise数量。我们可以封装一个并发控制器,接收任务数组和最大并发数,按需执行任务。
实现思路:
class PromisePool {
constructor(tasks, maxConcurrent) {
this.tasks = tasks;
this.maxConcurrent = maxConcurrent;
this.running = 0;
this.queue = [...tasks];
this.results = [];
}
<p>async run() {
const execute = async () => {
while (this.queue.length > 0) {
if (this.running < this.maxConcurrent) {
this.running++;
const task = this.queue.shift();
try {
const result = await task();
this.results.push({ status: 'fulfilled', value: result });
} catch (error) {
this.results.push({ status: 'rejected', error });
} finally {
this.running--;
execute(); // 触发下一个
}
break; // 每次只启动一个任务
}
}
};</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">// 启动初始并发
const starters = Array(Math.min(this.maxConcurrent, this.tasks.length))
.fill(0).map(execute);
await Promise.all(starters);
return this.results;} }
使用方式:
立即学习“Java免费学习笔记(深入)”;
const tasks = [
() => fetch('/api/1').then(r => r.json()),
() => fetch('/api/2').then(r => r.json()),
// 更多任务...
];
<p>new PromisePool(tasks, 3).run().then(console.log);
防抖(Debounce)用于延迟执行函数,直到连续调用停止一段时间后才执行最后一次。适用于搜索框输入、窗口调整等场景。
核心逻辑:
function debounce(fn, delay) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
<p>// 使用示例
const search = debounce(query => {
console.log('搜索:', query);
}, 300);</p><p>inputElement.addEventListener('input', e => {
search(e.target.value);
});
某些场景下需要双重控制。例如用户频繁提交异步操作(如上传文件),既要防抖减少触发次数,又要对实际执行的任务进行并发限制。
组合策略:
const uploadTasks = [/* 上传函数数组 */];
const pool = new PromisePool(uploadTasks, 2);
<p>const triggerUpload = debounce(async () => {
console.log('开始批量上传');
const result = await pool.run();
console.log('上传完成', result);
}, 500);
基本上就这些。合理使用Promise限流和防抖,能显著提升前端应用的健壮性和响应体验。关键是根据业务需求选择合适的策略组合。不复杂但容易忽略细节。
以上就是JavaScript并发控制_Promise限流与防抖策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号