Advertisement
Guest User

Untitled

a guest
Oct 17th, 2020
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. class ParallelRunner {
  2. private funQueue: (() => Promise<any>)[] = [];
  3. private funRunning: number = 0;
  4.  
  5. constructor(private _parallelFunctions: number) {}
  6.  
  7. public get parallelFunctions(): number {
  8. return this._parallelFunctions;
  9. }
  10.  
  11. public set parallelFunctions(v: number) {
  12. this._parallelFunctions = v;
  13. this.runNext();
  14. }
  15.  
  16. private addFunction(f: () => Promise<any>): void {
  17. if (this.funRunning >= this._parallelFunctions) {
  18. this.funQueue.push(f);
  19. } else {
  20. this.funRunning += 1;
  21. f();
  22. }
  23. }
  24.  
  25. private runNext(): void {
  26. while (this.funRunning < this._parallelFunctions) {
  27. const f = this.funQueue.shift();
  28. if (f === undefined) {
  29. return;
  30. }
  31. this.funRunning += 1;
  32. f();
  33. }
  34. }
  35.  
  36. run<T extends readonly unknown[], R>(
  37. f: (...args: [...T]) => Promise<R>,
  38. ...args: T
  39. ): Promise<R> {
  40. return new Promise((res, rej) => {
  41. let fun = async () => {
  42. try {
  43. res(await f(...args));
  44. } catch (e: any) {
  45. rej(e);
  46. } finally {
  47. this.runNext();
  48. }
  49. };
  50. this.addFunction(fun);
  51. });
  52. }
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement