1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2025-07-03 00:47:20 +02:00
Files
pigallery2/src/backend/model/threading/TaskExecuter.ts

34 lines
890 B
TypeScript
Raw Normal View History

2022-04-04 19:37:31 +02:00
import { TaskQue } from './TaskQue';
2018-12-08 18:17:33 +01:00
export interface ITaskExecuter<I, O> {
execute(input: I): Promise<O>;
}
export class TaskExecuter<I, O> implements ITaskExecuter<I, O> {
private taskQue = new TaskQue<I, O>();
private taskInProgress = 0;
private run = async () => {
if (this.taskQue.isEmpty() || this.taskInProgress >= this.size) {
return;
}
this.taskInProgress++;
const task = this.taskQue.get();
try {
task.promise.resolve(await this.worker(task.data));
} catch (err) {
task.promise.reject(err);
}
this.taskQue.ready(task);
this.taskInProgress--;
process.nextTick(this.run);
};
2022-04-04 19:37:31 +02:00
constructor(private size: number, private worker: (input: I) => Promise<O>) {}
2018-12-08 18:17:33 +01:00
execute(input: I): Promise<O> {
const promise = this.taskQue.add(input).promise.obj;
this.run().catch(console.error);
return promise;
}
}