File size: 1,681 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class ConcurrencyQueue {
  constructor(maxConcurrency = 2) {
    this.maxConcurrency = maxConcurrency;
    this.runningCount = 0;
    this.queue = [];
  }

  enqueue(taskFn, { signal } = {}) {
    return new Promise((resolve, reject) => {
      // ์ทจ์†Œํ•œ ๋Œ€๊ธฐ ํ•ญ๋ชฉ๋งŒ ํšŒ์ˆ˜ํ•œ๋‹ค. ์‹คํ–‰ ์ค‘์ธ ๋‹ค๋ฅธ ์ž‘์—…์ด๋‚˜ ์ „์ฒด ํ๋ฅผ ๋น„์šฐ์ง€ ์•Š๋Š”๋‹ค.
      const cleanup = () => signal?.removeEventListener('abort', abort);
      const entry = { taskFn, resolve, reject, cleanup };
      const abort = () => {
        const index = this.queue.indexOf(entry);
        if (index >= 0) this.queue.splice(index, 1);
        cleanup();
        reject(new Error('Queued request cancelled'));
      };
      if (signal?.aborted) { abort(); return; }
      signal?.addEventListener('abort', abort, { once: true });
      this.queue.push(entry);
      this.next();
    });
  }

  next() {
    if (this.runningCount >= this.maxConcurrency) {
      return;
    }
    if (this.queue.length === 0) {
      return;
    }

    const { taskFn, resolve, reject, cleanup } = this.queue.shift();
    cleanup();
    this.runningCount++;

    Promise.resolve()
      .then(() => taskFn())
      .then(result => {
        this.runningCount = Math.max(0, this.runningCount - 1);
        resolve(result);
        this.next();
      })
      .catch(err => {
        this.runningCount = Math.max(0, this.runningCount - 1);
        reject(err);
        this.next();
      });
  }

  cancelAll() {
    const pending = this.queue.splice(0);
    for (const { reject, cleanup } of pending) {
      cleanup();
      reject(new Error('Queue cancelled'));
    }
  }
}

module.exports = { ConcurrencyQueue };