关注
可以了,还有一个问题,为什么in time out:400先于3输出? class Scheduler {
race() {
return Promise.race([...this.main]).then(() => {
// console.log(`main size ${this.main.size}`)
if (this.main.size < 2) {
let willRun = this.queue.shift()();
this.main.add(willRun);
willRun.then(() => {
this.main.delete(willRun);
});
return willRun
} else {
console.log('have to wait')
return this.race();
}
});
}
add(promiseCreator) {
if (this.queue === undefined) this.queue = [];
if (this.main === undefined) this.main = new Set();
this.queue.push(promiseCreator);
if (this.queue.length && this.main.size < 2) {
let willRun = this.queue.shift()();
this.main.add(willRun);
willRun.then(() => {
this.main.delete(willRun);
});
return willRun;
} else {
return this.race();
}
}
}
const timeout = time =>
new Promise(resolve => {
console.log("in timeout:", time);
setTimeout(() => {
resolve();
//console.log(`${time}timeout`);
}, 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"); // output: 2 3 1 4 // 一开始,1、2 两个任务进入队列 // 500ms 时,2 完成,输出 2,任务 3 进队 // 800ms 时,3 完成,输出 3,任务 4 进队 // 1000ms 时,1 完成,输出 1 // 1200ms 时,4 完成,输出 4
查看原帖
点赞 2
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 职场捅娄子大赛 #
369774次浏览 3769人参与
# 什么专业适合考公 #
32238次浏览 207人参与
# 写给毕业5年后的自己 #
13432次浏览 241人参与
# 秋招被确诊为…… #
157969次浏览 715人参与
# 安克创新求职进展汇总 #
35686次浏览 425人参与
# 找实习你看重大厂光环还是业务方向 #
11199次浏览 86人参与
# 软开人,秋招你打算投哪些公司呢 #
97597次浏览 925人参与
# 你的房租占工资的比例是多少? #
29687次浏览 333人参与
# 考研对你找工作产生了哪些影响? #
17069次浏览 148人参与
# 蚂蚁求职进展汇总 #
104993次浏览 1112人参与
# 机械人怎么评价今年的比亚迪 #
54724次浏览 183人参与
# 计算机专业还有必要去大厂卷吗 #
23264次浏览 120人参与
# 你最满意的offer薪资是哪家公司? #
27439次浏览 149人参与
# 你觉得技术面多长时间合理? #
95056次浏览 690人参与
# 每人推荐一个小而美的高薪公司 #
74619次浏览 1364人参与
# kpi面有什么特征 #
41511次浏览 329人参与
# 工作压力大怎么缓解 #
82764次浏览 948人参与
# 秋招提前批启动你开冲了吗 #
119708次浏览 1908人参与
# 打杂的实习你会去吗? #
112054次浏览 973人参与
# 牛友打假中心 #
90439次浏览 2652人参与