2017-08-11 03:43:20 +00:00
|
|
|
function createMutex(doWork) {
|
|
|
|
const mutex = {}
|
|
|
|
|
2017-11-08 16:57:15 +00:00
|
|
|
return function(key, payload, callback) {
|
2017-08-11 03:43:20 +00:00
|
|
|
if (mutex[key]) {
|
|
|
|
mutex[key].push(callback)
|
|
|
|
} else {
|
2017-11-08 16:57:15 +00:00
|
|
|
mutex[key] = [
|
|
|
|
function() {
|
|
|
|
delete mutex[key]
|
|
|
|
},
|
|
|
|
callback
|
|
|
|
]
|
2017-08-11 03:43:20 +00:00
|
|
|
|
2017-11-08 16:57:15 +00:00
|
|
|
doWork(payload, function(error, value) {
|
|
|
|
mutex[key].forEach(function(callback) {
|
2017-08-11 03:43:20 +00:00
|
|
|
callback(error, value)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = createMutex
|