-
Notifications
You must be signed in to change notification settings - Fork 1
/
createLocker.js
48 lines (42 loc) · 1 KB
/
createLocker.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
'use strict'
const createLock = require('./createLock.js')
const globalLock = require('./lib/globalLock.js')
function createLocker (onEmpty) {
const locks = {}
const global = globalLock(function () {
for (const _ in locks) {
return false
}
return true
})
function getLock (key) {
let lock = locks[key]
if (!lock) {
lock = createLock(function () {
delete locks[key]
setImmediate(function () {
global.trigger()
})
})
locks[key] = lock
}
global.repeat(onEmpty)
return lock
}
function createLocker (key, process, timeout) {
return getLock(key)(process, timeout)
}
function released (key, onReleased) {
if (typeof key === 'function') {
return released(null, key)
}
if (key) {
return getLock(key).released(onReleased)
}
return global.released(onReleased)
}
createLocker.released = released
return createLocker
}
createLocker.default = createLocker
module.exports = createLocker