forked from almost/through2-concurrent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththrough2-concurrent.js
More file actions
90 lines (78 loc) · 2.39 KB
/
Copy paththrough2-concurrent.js
File metadata and controls
90 lines (78 loc) · 2.39 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Like through2 except execute in parallel with a set maximum
// concurrency
"use strict";
var through2 = require('through2');
module.exports = function concurrentThrough (options, transform, flush) {
var concurrent = 0, lastCallback = null, pendingFlush = null, concurrency;
if (typeof options === 'function') {
flush = transform;
transform = options;
options = {};
}
var maxConcurrency = options.maxConcurrency || 16;
function _transform (message, enc, callback) {
var self = this;
var callbackCalled = false;
concurrent++;
if (concurrent < maxConcurrency) {
// Ask for more right away
callback();
} else {
// We're at the concurrency limit, save the callback for
// when we're ready for more
lastCallback = callback;
}
transform.call(this, message, enc, function (err) {
// Ignore multiple calls of the callback (shouldn't ever
// happen, but just in case)
if (callbackCalled) return;
callbackCalled = true;
if (err) {
self.emit('error', err);
} else if (arguments.length > 1) {
self.push(arguments[1]);
}
concurrent--;
if (lastCallback) {
var cb = lastCallback;
lastCallback = null;
cb();
}
if (concurrent === 0 && pendingFlush) {
pendingFlush();
pendingFlush = null;
}
});
}
// Provide a default implementation of the 'flush' argument so that
// the waiting code below can stay simple. We need to pass in flush
// to through2 even if the caller has not given us a flush argument
// so that it will wait for all transform callbacks to complete
// before emitting an "end" event.
if (typeof flush !== 'function') {
flush = function (callback) {
callback();
};
}
function _flush (callback) {
// Ensure that flush isn't called until all transforms are complete
if (concurrent === 0) {
flush.call(this,callback);
} else {
pendingFlush = flush.bind(this, callback);
}
}
return through2(options, _transform, _flush);
};
module.exports.obj = function (options, transform, flush) {
if (typeof options === 'function') {
flush = transform;
transform = options;
options = {};
}
options.objectMode = true;
if (options.highWaterMark == null) {
options.highWaterMark = 16;
}
return module.exports(options, transform, flush);
};