unpkg/server/middleware/utils/createMutex.js

25 lines
459 B
JavaScript
Raw Normal View History

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