36 lines
743 B
JavaScript
36 lines
743 B
JavaScript
export default class TaskRunner {
|
|
constructor(concurrencyLimit = 1) {
|
|
this.queue = [];
|
|
this.running = 0;
|
|
this.concurrencyLimit = concurrencyLimit;
|
|
}
|
|
|
|
execute() {
|
|
if (this.running >= this.concurrencyLimit || this.queue.length === 0) {
|
|
return;
|
|
}
|
|
|
|
const task = this.queue.shift();
|
|
this.running += 1;
|
|
task();
|
|
}
|
|
|
|
async push(fn) {
|
|
return new Promise((resolve, reject) => {
|
|
const task = async () => {
|
|
try {
|
|
const result = await fn();
|
|
resolve(result);
|
|
} catch (error) {
|
|
reject(error);
|
|
} finally {
|
|
this.running -= 1;
|
|
this.execute();
|
|
}
|
|
}
|
|
|
|
this.queue.push(task);
|
|
this.execute();
|
|
});
|
|
}
|
|
} |