-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
40 lines (33 loc) · 893 Bytes
/
index.js
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
'use strict';
class Mutex {
constructor() {
// Item at index 0 is the caller with the lock: [ <has the lock>, <waiting>, <waiting>, ... ]
this.queue = [];
}
acquire({ timeout = false } = {}) {
const resolveNext = () => {
clearTimeout(this.queue[0].timer);
this.queue[0].resolve({
release: () => {
this.queue.shift();
if (this.queue.length > 0) {
resolveNext(this.queue);
}
}
})
};
return new Promise((resolve, reject) => {
this.queue.push({
resolve,
timer: timeout ? setTimeout(() => {
this.queue.splice(this.queue.findIndex(item => item.resolve === resolve), 1);
reject('Queue timeout');
}, timeout) : null
});
if (this.queue.length === 1) {
resolveNext(this.queue);
}
});
}
}
module.exports = Mutex;