js 归纳总结 方法合集
这一篇单独放一些更偏“场景题”的实现,和 jsFuncs 那种大而全的工具函数表区分开。量不多,但更适合补几个常见思路。
1. 并发控制
废话不说直接上代码
class TaskContral {
constructor(concurrentCount = 3) {
this.concurrentCount = concurrentCount; // 并发数量
this.tasks = []; // 任务列表
this.runnningCount = 0; // 执行中的任务数量
}
// 添加任务
add(task) {
return new Promise((resolve, reject) => {
this.tasks.push({
task,
resolve,
reject,
});
this.run();
});
}
// 任务执行
run() {
while (this.tasks.length > 0 && this.runnningCount < this.concurrentCount) {
// 取出任务队列第一项
const { task, resolve, reject } = this.tasks.shift();
// 执行数量 + 1
this.runnningCount++;
// 任务执行 then 返回 resolve, reject
task()
.then(resolve, reject)
.finally(() => {
// finally 执行之后任务数量 -1
this.runnningCount--;
// 继续递归执行run方法
this.run();
});
}
}
}
// 测试
function timeout(time) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, time);
});
}
const taskContral = new TaskContral(3);
function addTask(time, name) {
taskContral
.add(() => timeout(time))
.then(() => {
console.log(`任务${name}执行完成`);
});
}
addTask(1000, 1); // 1000后输出,任务1执行完成
addTask(1000, 2); // 1000后输出,任务2执行完成
addTask(1000, 3); // 1000后输出,任务3执行完成
addTask(1000, 4); // 2000后输出,任务4执行完成
addTask(1000, 5); // 2000后输出,任务5执行完成
addTask(1000, 6); // 2000后输出,任务6执行完成