aboutsummaryrefslogtreecommitdiff
path: root/src/queue.js
blob: 589425e572dbeae447a369f609c907780b64e7fd (plain) (blame)
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
class Queue {
  constructor() {
    this.running = false;
    this.queue = [];
  }

  add(fn) {
    const promise = new Promise(resolve => {
      this.queue.push(async () => {
        await Promise.resolve(fn());
        resolve();
      });

      if (! this.running) this.next();
    });

    return promise;
  }

  next() {
    this.running = true;

    if (this.queue.length === 0) {
      this.running = false;
      return;
    }

    const fn = this.queue.shift();
    new Promise(resolve => {
      // Either fn() completes or the timeout of 10sec is reached
      fn().then(resolve);
      setTimeout(resolve, 10000);
    }).then(() => this.next());
  }
}

module.exports = {
  Queue,
  messageQueue: new Queue()
};