We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
class Scheduler { constructor() { this.queue = []; // 存储任务的队列 this.maxConcurrent = 2; // 最大并发数 this.runningCount = 0; // 当前正在运行的任务数 } add(promiseCreator) { return new Promise((resolve, reject) => { // 将任务添加到队列中 this.queue.push({ promiseCreator, resolve, reject }); // 如果当前正在运行的任务数小于最大并发数,则执行任务 if (this.runningCount < this.maxConcurrent) { this.runTask(); } }); } runTask() { if (this.queue.length === 0) return; // 队列为空,直接返回 const { promiseCreator, resolve, reject } = this.queue.shift(); this.runningCount++; // 当前正在运行的任务数加一 promiseCreator() .then(resolve) .catch(reject) .finally(() => { this.runningCount--; // 当前正在运行的任务数减一 this.runTask(); // 继续执行下一个任务 }); } } const timeout = (time) => new Promise((resolve) => setTimeout(resolve, time)); const scheduler = new Scheduler(); const addTask = (time, order) => { scheduler.add(() => timeout(time)).then(() => console.log(order)); }; addTask(1000, "1"); addTask(500, "2"); addTask(300, "3"); addTask(400, "4");
The text was updated successfully, but these errors were encountered:
No branches or pull requests
The text was updated successfully, but these errors were encountered: