-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb-lock.js
More file actions
46 lines (38 loc) · 1003 Bytes
/
Copy pathdb-lock.js
File metadata and controls
46 lines (38 loc) · 1003 Bytes
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
class DBLock {
constructor() {
this.lockRequestQueue = [];
this.locked = false;
}
/**
* Acquire a database lock
*
* @returns {Promise<Function>} - lock release function
*/
async acquire() {
if ( this.locked ) {
const acquisitionPromise = new Promise( ( resolve, reject ) => {
this.lockRequestQueue.push( resolve );
});
return acquisitionPromise;
} else {
this.locked = true;
return this.release.bind( this );
}
}
/**
* The release function returned by acquire that either resolves the next
* lock request in the lock request queue with a release or sets locked to
* false.
*
* @returns {Promise<undefined>} - database lock released
*/
async release() {
if ( this.lockRequestQueue.length ) {
const requestResolve = this.lockRequestQueue.shift();
requestResolve( this.release.bind( this ) );
} else {
this.locked = false;
}
}
}
module.exports = DBLock;