-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (46 loc) · 1.18 KB
/
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
41
42
43
44
45
46
47
48
49
50
/**
* SemaphorePromise class
* @typedef {Object} SemaphorePromise
*/
export class SemaphorePromise {
/**
* @constructor
* @param {number} n
*/
constructor(n) {
this.n = n;
this.wait_promise = null;
this.wait_promise_cb = null;
}
async acquire() {
const self = this;
while (self.n==0) {
if (!self.wait_promise) {
self.wait_promise = new Promise(function(resolve) {
self.wait_promise_cb = resolve;
});
}
// console.log("waiting ...");
await self.wait_promise;
// console.log("waiting ... done");
}
--(self.n);
return self.n;
}
release() {
++(this.n);
const wait_cb = this.wait_promise_cb;
this.wait_promise_cb = null;
this.wait_promise = null;
if (wait_cb) wait_cb();
}
/**
*
* @param {*} get_promise a function that returns a promise to be wrapped
* @returns the wrapped promise
*/
with(get_promise) {
const self = this;
return self.acquire().then(()=>get_promise()).finally(()=>self.release())
}
}