-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
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
028.async-concurrent-scheduler #28
Comments
class Scheduler {
constructor(num = 2) {
this.max = num;
this.queue = [];
this.count = 0;
}
add(promiseCreator) {
return new Promise((resolve) => {
promiseCreator._resolve = resolve; // 关键点,怎么缓存这个 resolve; reject 同理
this.queue.push(promiseCreator);
this.run();
});
}
run() {
if (this.count >= this.max || this.queue.length === 0) return;
this.count++;
const promise = this.queue.shift();
promise()
.then(res => {
promise._resolve(res);
}).finally(() => {
this.count--;
this.run();
})
}
} |
class Scheduler {
constructor(num = 2) {
this.max = num;
this.queue = [];
this.count = 0;
}
add(task) {
return new Promise((resolve) => {
// 用对象包装一下,保存 resolve
this.queue.push({
resolve,
task
});
this.run();
});
}
run() {
if (this.count >= this.max || this.queue.length === 0) return;
this.count++;
const { task, resolve } = this.queue.shift();
task()
.then(res => {
resolve(res);
}).finally(() => {
this.count--;
this.run();
})
}
} |
简单的变种,这个不需要缓存resolveconst urls = [
{
link: "link1",
time: 1000,
},
{
link: "link2",
time: 500,
},
{
link: "link3",
time: 300,
},
{
link: "link4",
time: 400,
},
];
// 模拟异步加载
function request(url) {
return new Promise((resolve) => {
console.log(url.link + "- start");
setTimeout(() => {
console.log(url.link + "- end");
resolve();
}, url.time);
});
}
class Scheduler {
constructor(n = 2) {
this.max = n;
this.currentCount = 0;
this.taskQueue = [];
}
add(task) {
this.taskQueue.push(task);
this.run();
}
run() {
if (this.taskQueue.length === 0 || this.currentCount >= this.max)
return;
this.currentCount++;
const fn = this.taskQueue.shift();
fn()
.finally(() => {
this.currentCount--;
this.run();
})
}
}
const scheduler = new Scheduler();
urls.forEach((url) => {
scheduler.add(() => request(url));
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
实现一个带并发限制的异步调度器,保证同时运行的任务最多有两个。
完善下面代码中的 Scheduler 类,使得以下程序能正确输出。
The text was updated successfully, but these errors were encountered: