UNPKG

@node-dlc/core

Version:
55 lines 1.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AsyncProcessingQueue = void 0; const events_1 = require("events"); const Queue_1 = require("./Queue"); /** * Serializes execution of events. This class is constructed with * a delegate function that is executed for each item that is enqueued. */ class AsyncProcessingQueue extends events_1.EventEmitter { constructor(fn) { super(); this._fn = fn; this._queue = new Queue_1.Queue(); this._flush = this._flush.bind(this); } /** * Adds a new item to the processing queue */ enqueue(value) { this._queue.enqueue(value); // Postpone flushing until end of event loop to allow multiple operations // to enqueue. This handle will be cleared once flushing has completed. if (!this._flushHandle) this._flushHandle = setImmediate(this._flush); } /** * Gets the number of pending items in the processor queue * @type {number} */ get size() { return this._queue.length; } async _flush() { // emit that flushing is starting this.emit('flushing'); // process all items on the queue, even items that // are added to the queue while flushing is occuring while (this._queue.length > 0) { try { const value = this._queue.dequeue(); await this._fn(value); } catch (ex) { this.emit('error', ex); } } // emit flushing has completed this.emit('flushed'); // clear flush handle so that next enqueue will trigger a flush this._flushHandle = undefined; } } exports.AsyncProcessingQueue = AsyncProcessingQueue; //# sourceMappingURL=AsyncProcessingQueue.js.map