| 236 | } |
| 237 | |
| 238 | runWithConcurrency(task, priority = 'normal') { |
| 239 | return new Promise((resolve, reject) => { |
| 240 | const run = async () => { |
| 241 | this.activeRequestCount += 1; |
| 242 | try { |
| 243 | const result = await task(); |
| 244 | resolve(result); |
| 245 | } catch (error) { |
| 246 | reject(error); |
| 247 | } finally { |
| 248 | this.activeRequestCount = Math.max(0, this.activeRequestCount - 1); |
| 249 | this.flushQueue(); |
| 250 | } |
| 251 | }; |
| 252 | |
| 253 | if (this.activeRequestCount < this.maxConcurrentRequests) { |
| 254 | run(); |
| 255 | return; |
| 256 | } |
| 257 | |
| 258 | if (priority === 'high') { |
| 259 | this.requestQueue.unshift(run); |
| 260 | } else { |
| 261 | this.requestQueue.push(run); |
| 262 | } |
| 263 | }); |
| 264 | } |
| 265 | |
| 266 | flushQueue() { |
| 267 | while (this.activeRequestCount < this.maxConcurrentRequests && this.requestQueue.length > 0) { |