| 35 | } |
| 36 | |
| 37 | async processQueue() { |
| 38 | if (this.processing || this.queue.length === 0) { |
| 39 | return; |
| 40 | } |
| 41 | |
| 42 | this.processing = true; |
| 43 | |
| 44 | while (this.queue.length > 0) { |
| 45 | const now = Date.now(); |
| 46 | |
| 47 | if (now - this.lastProcessTime >= 1000) { |
| 48 | this.taskCount = 0; |
| 49 | this.lastProcessTime = now; |
| 50 | } |
| 51 | |
| 52 | if ( |
| 53 | this.taskCount >= this.maxTasksPerSecond || |
| 54 | this.tasksWaiting >= this.maxSimultaneousTasks |
| 55 | ) { |
| 56 | const waitTime = 1000 - (now - this.lastProcessTime); |
| 57 | await this.sleep(waitTime); |
| 58 | continue; |
| 59 | } |
| 60 | |
| 61 | const task = this.queue.shift(); |
| 62 | this.taskCount++; |
| 63 | this.tasksWaiting++; |
| 64 | |
| 65 | try { |
| 66 | const result = await task.taskFunction.apply(task.that, task.args); |
| 67 | this.tasksWaiting--; |
| 68 | task.resolve(result); |
| 69 | } catch (error) { |
| 70 | task.reject(error); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | this.processing = false; |
| 75 | } |
| 76 | |
| 77 | sleep(ms) { |
| 78 | return new Promise((resolve) => setTimeout(resolve, ms)); |