1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.Mutex = void 0;
|
4 | class Mutex {
|
5 | constructor() {
|
6 | this.busy = false;
|
7 | this.queue = [];
|
8 | }
|
9 | synchronize(task) {
|
10 | return new Promise((resolve, reject) => {
|
11 | this.queue.push([task, resolve, reject]);
|
12 | if (!this.busy) {
|
13 | this.dequeue();
|
14 | }
|
15 | });
|
16 | }
|
17 | dequeue() {
|
18 | this.busy = true;
|
19 | const next = this.queue.shift();
|
20 | if (next) {
|
21 | return this.execute(next);
|
22 | }
|
23 | this.busy = false;
|
24 | }
|
25 | execute(record) {
|
26 | const [task, resolve, reject] = record;
|
27 | return task()
|
28 | .then(resolve, reject)
|
29 | .then(() => {
|
30 | this.dequeue();
|
31 | });
|
32 | }
|
33 | }
|
34 | exports.Mutex = Mutex;
|