-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathguard.js
61 lines (51 loc) · 1.23 KB
/
guard.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
module.exports = function(Promise) {
//
// Guards against excessive concurrency. Returns a new function which is identical to the given
// function, except that the new function will only run a limited number of concurrent instances
// of itself. Additional calls will be queued.
//
// @param {limit} optional; the maximum number of concurrent calls allowed
// @param {func} the function to guard
// @return function
//
return function(limit, func) {
if (arguments.length === 1) {
func = limit;
limit = 1;
}
var queue = [ ];
var running = 0;
return function() {
var args = arguments;
var deferred = defer();
queue.push([ this, args, deferred ]);
next();
return deferred.promise;
};
function next() {
if (running < limit) {
var data = queue.shift();
running++;
func.apply(data[0], data[1])
.then(
function(result) {
running--;
data[2].resolve(result);
},
function(err) {
running--;
data[2].reject(err);
}
);
}
}
function defer() {
var deferred = { };
deferred.promise = new Promise(function(resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
}
};
};