UNPKG

event-emitters

Version:
58 lines 2.2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventEmitterAsyncIterator = void 0; var Queue_1 = require("./Queue"); /** * An async iterator implemented with an efficient queue. * * Make the async iterator also fulfil AsyncIterable, which is pretty pointless * but needed to support certain APIs that are not implemented correctly. */ var EventEmitterAsyncIterator = /** @class */ (function () { function EventEmitterAsyncIterator(eventSource) { this.eventSource = eventSource; this.emitted = new Queue_1.Queue(); // this will only contain listeners when `emitted` is empty this.pendingListens = new Queue_1.Queue(); this.onEmit = this.onEmit.bind(this); eventSource.subscribe(this.onEmit); } EventEmitterAsyncIterator.prototype.onEmit = function (value) { if (this.pendingListens.length) { this.pendingListens.dequeue()({ done: false, value: value }); } else { this.emitted.enqueue(value); } }; EventEmitterAsyncIterator.prototype.next = function () { var _this = this; if (this.emitted.length) { return Promise.resolve({ done: false, value: this.emitted.dequeue() }); } else { return new Promise(function (resolve) { _this.pendingListens.enqueue(resolve); }); } }; EventEmitterAsyncIterator.prototype.return = function () { this.eventSource.unsubscribe(this.onEmit); this.emitted.destroy(); this.pendingListens.destroy(); return Promise.resolve({ value: undefined, done: true }); }; EventEmitterAsyncIterator.prototype.throw = function (error) { this.eventSource.unsubscribe(this.onEmit); this.emitted.destroy(); this.pendingListens.destroy(); return Promise.reject(error); }; // *sigh* EventEmitterAsyncIterator.prototype[Symbol.asyncIterator] = function () { return this; }; return EventEmitterAsyncIterator; }()); exports.EventEmitterAsyncIterator = EventEmitterAsyncIterator; //# sourceMappingURL=EventEmitterAsyncIterator.js.map