Closed francecil closed 1 year ago
class AsyncQueue {
constructor(concurrent) {
/** 可同时执行的任务数 */
this.concurrent = concurrent
/** 存放待执行的任务 */
this.queue = []
/** 当前正在执行的任务数 */
this.runningTasks = 0
}
push(job) {
if(this.runningTasks < this.concurrent) {
this.runningTasks ++
this.runTask(job)
} else {
// 达到最大并发次数,放入队列
this.queue.push(job)
}
}
next() {
const headTask = this.queue.shift()
if(headTask) {
this.runTask(headTask)
}
}
async runTask(job) {
try {
await job()
} catch (error) {
console.log(error)
}
this.runningTasks--
this.next()
}
}
实现一个异步队列 AsyncQueue ,仅允许同时执行 n 个任务,参考如下示例
预期输出如下: