1 | "use strict"
|
2 |
|
3 | const defaultMaxRunning = 50
|
4 |
|
5 | var limit = module.exports = function (func, maxRunning) {
|
6 | let running = 0
|
7 | const queue = []
|
8 | if (!maxRunning) maxRunning = defaultMaxRunning
|
9 | return function limited () {
|
10 | const self = this
|
11 | const args = Array.prototype.slice.call(arguments)
|
12 | if (running >= maxRunning) {
|
13 | queue.push(args)
|
14 | return
|
15 | }
|
16 | const cb = typeof args[args.length-1] === 'function' && args.pop()
|
17 | ++ running
|
18 | args.push(function () {
|
19 | const cbargs = arguments
|
20 | -- running
|
21 | cb && process.nextTick(function() {
|
22 | cb.apply(self, cbargs)
|
23 | })
|
24 | if (queue.length) {
|
25 | const next = queue.shift()
|
26 | limited.apply(self, next)
|
27 | }
|
28 | })
|
29 | func.apply(self, args)
|
30 | }
|
31 | }
|
32 |
|
33 | module.exports.method = function (classOrObj, method, maxRunning) {
|
34 | if (typeof classOrObj === 'function') {
|
35 | var func = classOrObj.prototype[method]
|
36 | classOrObj.prototype[method] = limit(func, maxRunning)
|
37 | } else {
|
38 | var func = classOrObj[method]
|
39 | classOrObj[method] = limit(func, maxRunning)
|
40 | }
|
41 | }
|