mirror of
https://github.com/bendtherules/JSQuestions.git
synced 2026-08-19 00:30:48 +00:00
async scheduler 1
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
class TaskScheduler {
|
||||
constructor(concurrency = 1) {
|
||||
this.queue = [];
|
||||
this.isProcessing = false;
|
||||
this.concurrencyLimit = concurrency;
|
||||
this.runningCount = 0;
|
||||
}
|
||||
|
||||
addTask(taskFn) {
|
||||
const { promise, resolve, reject } = Promise.withResolvers();
|
||||
this.queue.push({
|
||||
taskFn,
|
||||
resolve,
|
||||
reject,
|
||||
});
|
||||
|
||||
this._processQueue();
|
||||
return promise;
|
||||
}
|
||||
|
||||
_processQueue() {
|
||||
if (!this.isProcessing) return;
|
||||
|
||||
while (this.runningCount < this.concurrencyLimit && this.queue.length > 0) {
|
||||
const {
|
||||
taskFn,
|
||||
resolve,
|
||||
reject,
|
||||
} = this.queue.shift();
|
||||
|
||||
this.runningCount++;
|
||||
|
||||
// Ensure taskFn errors are captured as rejections
|
||||
const taskPromise = Promise.resolve().then(() => taskFn());
|
||||
taskPromise.then(resolve, reject);
|
||||
taskPromise.finally(() => {
|
||||
this.runningCount--;
|
||||
this._processQueue();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
play(){
|
||||
this.isProcessing = true;
|
||||
this._processQueue();
|
||||
}
|
||||
|
||||
pause(){
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = TaskScheduler;
|
||||
Reference in New Issue
Block a user