queueable
Version:
Convert push-based streams to pull-based async iterables
67 lines (66 loc) • 3.09 kB
TypeScript
/// <reference types="node" />
import Deferred from '../Deferred';
import Buffer from '../Buffer';
import { PushAdapter } from '../common';
/**
* Async iterable iterator with a non-optional return method.
*/
export interface WrappedBalancer<A> extends AsyncIterableIterator<A> {
return(value?: A): Promise<IteratorResult<A>>;
throw?: undefined;
}
export interface Unpushed<A> {
result: IteratorResult<A>;
defer: Deferred<IteratorResult<A>>;
}
/**
* Balances a push queue with a pull queue, also known as a
* dropping-buffer channel, since the queues are FIFO and
* can be set to be bounded, i.e., to drop the oldest enqueued
* values if the limit is exceeded. The channel is unbounded
* by default.
*/
export default class Channel<A> implements PushAdapter<A> {
/** Pushed results waiting for pulls to resolve */
readonly pushBuffer: Buffer<Unpushed<A>>;
/** Unresolved pulls waiting for results to be pushed */
readonly pullBuffer: Buffer<Deferred<IteratorResult<A>>>;
/** Determines whether new values can be pushed or pulled */
private closed;
static fromDom: (type: keyof GlobalEventHandlersEventMap, target: import("../fromDom").Target<keyof GlobalEventHandlersEventMap, import("../fromDom").Listener<keyof GlobalEventHandlersEventMap>, boolean | AddEventListenerOptions>, options?: boolean | AddEventListenerOptions | undefined) => AsyncIterableIterator<UIEvent | Event | AnimationEvent | MouseEvent | InputEvent | FocusEvent | CompositionEvent | DragEvent | ErrorEvent | FormDataEvent | PointerEvent | KeyboardEvent | ProgressEvent<EventTarget> | SecurityPolicyViolationEvent | SubmitEvent | TouchEvent | TransitionEvent | WheelEvent>;
static fromEmitter: (type: string | symbol, emitter: NodeJS.EventEmitter) => AsyncIterableIterator<any>;
constructor(
/** Limit (bounds) after which the oldest buffered value is dropped. */
limit?: number);
/**
* Pull a promise of the next result.
*/
next(): Promise<IteratorResult<A>>;
/**
* Push the next result value.
*
* @param value - Result
* @param done - If true, closes the balancer when this result is resolved
* @throws Throws if the balancer is already closed
*/
push(value: A, done?: boolean): Promise<IteratorResult<A>>;
/**
* Returns itself, since {@link Channel} already implements the iterator protocol.
*/
[Symbol.asyncIterator](): this;
/**
* Closes the balancer; clears the queues and makes {@link Channel#next} only
* return `doneResult`.
*
* @param value - The result value to be returned
*/
return(value?: A): Promise<IteratorResult<A>>;
close(): void;
/**
* Convert {@link Channel} to a generic async iterable iterator to hide implementation details.
*
* @param onReturn - Optional callback for when the iterator is closed with {@link Channel#return}
* @throws Throws if called when closed
*/
wrap(onReturn?: () => void): WrappedBalancer<A>;
}