Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ParallelRunner {
- private funQueue: (() => Promise<any>)[] = [];
- private funRunning: number = 0;
- constructor(private _parallelFunctions: number) {}
- public get parallelFunctions(): number {
- return this._parallelFunctions;
- }
- public set parallelFunctions(v: number) {
- this._parallelFunctions = v;
- this.runNext();
- }
- private addFunction(f: () => Promise<any>): void {
- if (this.funRunning >= this._parallelFunctions) {
- this.funQueue.push(f);
- } else {
- this.funRunning += 1;
- f();
- }
- }
- private runNext(): void {
- while (this.funRunning < this._parallelFunctions) {
- const f = this.funQueue.shift();
- if (f === undefined) {
- return;
- }
- this.funRunning += 1;
- f();
- }
- }
- run<T extends readonly unknown[], R>(
- f: (...args: [...T]) => Promise<R>,
- ...args: T
- ): Promise<R> {
- return new Promise((res, rej) => {
- let fun = async () => {
- try {
- res(await f(...args));
- } catch (e: any) {
- rej(e);
- } finally {
- this.runNext();
- }
- };
- this.addFunction(fun);
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement