UNPKG

event-emitters

Version:
52 lines 1.63 kB
import { Queue } from './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. */ export class EventEmitterAsyncIterator { constructor(eventSource) { this.eventSource = eventSource; this.emitted = new Queue(); // this will only contain listeners when `emitted` is empty this.pendingListens = new Queue(); this.onEmit = this.onEmit.bind(this); eventSource.subscribe(this.onEmit); } onEmit(value) { if (this.pendingListens.length) { this.pendingListens.dequeue()({ done: false, value }); } else { this.emitted.enqueue(value); } } next() { if (this.emitted.length) { return Promise.resolve({ done: false, value: this.emitted.dequeue() }); } else { return new Promise((resolve) => { this.pendingListens.enqueue(resolve); }); } } return() { this.eventSource.unsubscribe(this.onEmit); this.emitted.destroy(); this.pendingListens.destroy(); return Promise.resolve({ value: undefined, done: true }); } throw(error) { this.eventSource.unsubscribe(this.onEmit); this.emitted.destroy(); this.pendingListens.destroy(); return Promise.reject(error); } // *sigh* [Symbol.asyncIterator]() { return this; } } //# sourceMappingURL=EventEmitterAsyncIterator.js.map