| 1 |
/* eslint max-statements: "off" */ |
| 2 |
|
| 3 |
// Limit number of concurrent function executions (to cLimit number). |
| 4 |
// Limited calls are queued. Optionaly maximum queue length can also be |
| 5 |
// controlled with qLimit value, any calls that would reach over that limit |
| 6 |
// would be discarded (its promise would resolve with "Too many calls" error) |
| 7 |
|
| 8 |
"use strict"; |
| 9 |
|
| 10 |
var toPosInt = require("es5-ext/number/to-pos-integer") |
| 11 |
, callable = require("es5-ext/object/valid-callable") |
| 12 |
, isValue = require("es5-ext/object/is-value") |
| 13 |
, eeUnify = require("event-emitter/unify") |
| 14 |
, deferred = require("../../deferred") |
| 15 |
, isPromise = require("../../is-promise") |
| 16 |
, assimilate = require("../../assimilate"); |
| 17 |
|
| 18 |
var resolve = deferred.resolve |
| 19 |
, reject = deferred.reject |
| 20 |
, apply = Function.prototype.apply |
| 21 |
, max = Math.max |
| 22 |
, gateReject; |
| 23 |
|
| 24 |
require("../promise/finally"); |
| 25 |
|
| 26 |
gateReject = function () { |
| 27 |
var e = new Error("Too many calls at the gate"); |
| 28 |
e.code = "DEFERRED_REJECTED_AT_GATE"; |
| 29 |
e.type = "deferred-gate-rejected"; |
| 30 |
return reject(e); |
| 31 |
}; |
| 32 |
|
| 33 |
module.exports = function (cLimit, qLimit) { |
| 34 |
var fn, count, decrement, unload, queue, run, result; |
| 35 |
fn = callable(this); |
| 36 |
cLimit = max(toPosInt(cLimit), 1); |
| 37 |
qLimit = !isValue(qLimit) || isNaN(qLimit) ? Infinity : toPosInt(qLimit); |
| 38 |
count = 0; |
| 39 |
queue = []; |
| 40 |
|
| 41 |
run = function (thisArg, args, def) { |
| 42 |
var localResult; |
| 43 |
try { |
| 44 |
localResult = apply.call(fn, thisArg, args); |
| 45 |
} catch (e) { |
| 46 |
if (!def) return reject(e); |
| 47 |
def.reject(e); |
| 48 |
return unload(); |
| 49 |
} |
| 50 |
localResult = assimilate(localResult); |
| 51 |
if (isPromise(localResult)) { |
| 52 |
if (def) eeUnify(def.promise, localResult); |
| 53 |
if (!localResult.resolved) { |
| 54 |
++count; |
| 55 |
if (def) def.resolve(localResult); |
| 56 |
return localResult.finally(decrement); |
| 57 |
} |
| 58 |
if (!localResult.failed) localResult = localResult.value; |
| 59 |
} |
| 60 |
if (!def) return resolve(localResult); |
| 61 |
def.resolve(localResult); |
| 62 |
return unload(); |
| 63 |
}; |
| 64 |
|
| 65 |
decrement = function () { |
| 66 |
--count; |
| 67 |
unload(); |
| 68 |
}; |
| 69 |
|
| 70 |
unload = function () { |
| 71 |
var data; |
| 72 |
if ((data = queue.shift())) run.apply(null, data); |
| 73 |
}; |
| 74 |
|
| 75 |
result = function () { |
| 76 |
var def; |
| 77 |
if (count >= cLimit) { |
| 78 |
if (queue.length < qLimit) { |
| 79 |
def = deferred(); |
| 80 |
queue.push([this, arguments, def]); |
| 81 |
return def.promise; |
| 82 |
} |
| 83 |
return gateReject(); |
| 84 |
} |
| 85 |
return run(this, arguments); |
| 86 |
}; |
| 87 |
result.returnsPromise = true; |
| 88 |
return result; |
| 89 |
}; |