hole
Version:
Async friendly, stream-based task consuming utility in Node.js
50 lines (49 loc) • 1.83 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const parallel_transform_stream_1 = __importDefault(require("parallel-transform-stream"));
class HoleTransform extends parallel_transform_stream_1.default {
constructor(asyncFn, options) {
super(Object.assign({}, options, { objectMode: true, transform: undefined, flush: undefined }));
// Ugly hack for ParallelTransform emitting `finish`
// when it **starts consuming last task**, not completes it.
// `pump` uses the event to call a callback afterward
// where we finish the whole streaming. See
// https://github.com/ubilabs/node-parallel-transform-stream/issues/2
this.finished = false;
this.consumingLength = 0;
this.asyncFn = asyncFn;
}
_parallelTransform(data, enc, callback) {
this.consumingLength++;
try {
const rv = this.asyncFn(data);
Promise.resolve(rv)
.then((resolved) => {
callback(null, resolved);
this.consumingLength--;
if (this.finished && this.consumingLength === 0) {
setImmediate(() => {
super.emit('finish');
});
}
})
.catch(callback);
}
catch (err) {
callback(err);
}
}
// noinspection JSUnusedGlobalSymbols
emit(...args) {
const [type] = args;
if (type === 'finish') {
this.finished = true;
return;
}
return super.emit.apply(this, args);
}
}
exports.HoleTransform = HoleTransform;