node/deps/npm/node_modules/inflight/inflight.js

45 lines
897 B
JavaScript
Raw Normal View History

2014-11-05 07:08:12 +08:00
var wrappy = require('wrappy')
2014-06-06 06:18:15 +08:00
var reqs = Object.create(null)
var once = require('once')
2014-11-05 07:08:12 +08:00
module.exports = wrappy(inflight)
2014-06-06 06:18:15 +08:00
function inflight (key, cb) {
if (reqs[key]) {
reqs[key].push(cb)
return null
} else {
reqs[key] = [cb]
return makeres(key)
}
}
2014-11-05 07:08:12 +08:00
function makeres (key) {
return once(function RES () {
2014-06-06 06:18:15 +08:00
var cbs = reqs[key]
2014-11-05 07:08:12 +08:00
var len = cbs.length
var args = slice(arguments)
for (var i = 0; i < len; i++) {
cbs[i].apply(null, args)
}
if (cbs.length > len) {
// added more in the interim.
// de-zalgo, just in case, but don't call again.
cbs.splice(0, len)
process.nextTick(function () {
RES.apply(null, args)
})
} else {
delete reqs[key]
}
})
}
function slice (args) {
var length = args.length
var array = []
for (var i = 0; i < length; i++) array[i] = args[i]
return array
2014-06-06 06:18:15 +08:00
}