Mark24
记录灵感、技术、思考
Promise实现的Scheduler
class Scheduler {
constructor() {
super();
this.queue = [];
this.maxCount = 2; // 最大并发数
this.runningCount = 0; // 当前正在运行的任务数
}
add(promiseCreator) {
this.queue.push(promiseCreator);
}
start() {
for (let i = 0; i < this.maxCount; i++) {
this.run();
}
}
run() {
if (this.queue.length === 0 || this.runningCount >= this.maxCount) {
return;
}
this.runningCount++;
const promiseCreator = this.queue.shift();
const promise = promiseCreator();
promise
.then(() => {
this.runningCount--;
this.run();
})
.catch(() => {
this.runningCount--;
this.run();
});
}
}
const timeout = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};
const scheduler = new Scheduler();
const addTask = (time, order) => {
scheduler.add(() => {
return timeout(time).then(() => console.log(order));
});
};
addTask(1000, 1);
addTask(500, 2);
addTask(300, 3);
addTask(400, 4);
scheduler.start();
使用 async、await 实现
class Scheduler {
constructor(maxCount) {
super()
this.maxCount = maxCount;
this.queue = [];
this.runningCount = 0;
}
add(fn) {
this.queue.push(fn);
}
async run() {
while (this.runningCount < this.maxCount && this.queue.length > 0) {
this.runningCount++;
const fn = this.queue.shift();
await fn();
this.runningCount--;
}
}
async start() {
while (this.queue.length > 0) {
await this.run();
}
}
}
const timeout = (time) => {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
};
const scheduler = new Scheduler(2);
const addTask = (time, order) => {
scheduler.add(async () => {
await timeout(time);
console.log(order);
});
};
addTask(1000, 1);
addTask(500, 2);
addTask(300, 3);
addTask(400, 4);
scheduler.start();