I want to create a task runner which run based on limit for eg. limit=3 i.e. run 3 task at a time, but it is not executing after given limit; below is the main code ;
what could be the issue here?
class TaskRunner {
#limit;
#taskQueue = [];
#taskCount = 0;
constructor(limit) {
this.#limit = limit;
}
run(fn, id) {
this.#taskQueue.push({ task: fn, id: id });
this.#taskCount++;
while(this.#taskCount <= this.#limit && this.#taskQueue.length > 0) {
const { task, id } = this.#taskQueue.shift();
task(id).then((p)=>{
console.log({p});
this.#taskCount--;
})
}
console.log(this.#taskCount);
}
}
const taskRunner = new TaskRunner(3);
const task = (arg)=>{
return new Promise((resolve)=>{
setTimeout(()=>{
console.log("Task Completed!", arg);
resolve(true);
}
, 2000)
}
)
}
;
taskRunner.run(task, 'id-1');
taskRunner.run(task, 'id-2');
taskRunner.run(task, 'id-3');
taskRunner.run(task, 'id-4');
taskRunner.run(task, 'id-5');
taskRunner.run(task, 'id-6');
taskRunner.run(task, 'id-7');
or is there any better way to handle this?