parallel-universe
Version:
The set of async flow control structures and promise utils.
66 lines (65 loc) • 2.47 kB
TypeScript
import { AbortablePromise } from './AbortablePromise';
/**
* The protocol provided to the {@link AsyncQueue} consumer, so it can acknowledge that the value was processed and
* should be removed from the queue.
*
* @template T The value taken from the queue.
*/
export type ValueAck<T> = [value: T, ack: (isTaken: boolean) => void];
/**
* Asynchronous queue decouples value producers and value consumers.
*
* @template T The value stored in the queue.
*/
export declare class AsyncQueue<T = any> {
/**
* The elements stored in the queue.
*/
private _elements;
/**
* The promise that resolves after the most recent take was acknowledged.
*/
private _promise;
/**
* Resolves a pending acknowledgement promise, so the consumer can obtain the value from the queue. `undefined` if
* there's no pending consumer.
*/
private _resolveTake?;
/**
* Returns the number of values stored in this queue.
*/
get size(): number;
/**
* Appends a new value to the end of the queue.
*
* @param value The value to append.
*/
append(value: T): this;
/**
* Returns a promise that is fulfilled with a value when it is available.
*
* Values are taken in the same order they were appended. Taken values are removed from the queue.
*
* @returns The promise that is fulfilled with a value that was added to the queue. Aborting the returned promise
* after the value was taken is a no-op.
*/
take(): AbortablePromise<T>;
/**
* Returns a promise that is fulfilled with a value and an acknowledgement callback.
*
* The promise is fulfilled when a value is available. Consequent consumers are blocked until the acknowledgement
* callback is invoked. Invoking acknowledgement callback multiple times is a no-op.
*
* **Note:** Be sure to always call an acknowledgement callback. Otherwise, consequent consumers would never be
* fulfilled.
*
* @returns A tuple that contains a value available in the queue, and a callback that acknowledges that the value was
* processed and should be removed from the queue. Aborting the returned promise after a consumer received an
* acknowledgement callback is a no-op.
*/
takeAck(): AbortablePromise<ValueAck<T>>;
/**
* Iterates over elements that are available in the queue.
*/
[Symbol.iterator](): IterableIterator<T>;
}