cancellationtoken
Version:
A composable token for cancelling asynchronous operations.
94 lines (93 loc) • 2.98 kB
TypeScript
/**
* A token that can be passed around to inform consumers of the token that a
* certain operation has been cancelled.
*/
declare class CancellationToken {
/**
* Whether the token is already cancelled.
*/
private _isCancelled;
/**
* Whether the token can be cancelled.
*/
readonly canBeCancelled: boolean;
private _reason;
private _callbacks?;
/**
* A cancellation token that is already cancelled.
*/
static readonly CANCELLED: CancellationToken;
/**
* A cancellation token that is never cancelled.
*/
static readonly CONTINUE: CancellationToken;
/**
* Whether the token has been cancelled.
*/
get isCancelled(): boolean;
/**
* Why this token has been cancelled.
*/
get reason(): any;
/**
* Make a promise that resolves when the async operation resolves,
* or rejects when the operation is rejected or this token is cancelled.
*/
racePromise<T>(asyncOperation: Promise<T>): Promise<T>;
/**
* Throw a {CancellationToken.CancellationError} if this token is cancelled.
*/
throwIfCancelled(): void;
/**
* Invoke the callback when this token is cancelled.
* If this token is already cancelled, the callback is invoked immediately.
* Returns a function that unregisters the cancellation callback.
*/
onCancelled(cb: (reason?: any) => void): () => void;
private constructor();
/**
* Create a {CancellationToken} and a method that cancels it.
*/
static create(): {
token: CancellationToken;
cancel: (reason?: any) => void;
};
/**
* Create a {CancellationToken} and a method that cancels it.
* The token will be cancelled automatically after the specified timeout in milliseconds.
*/
static timeout(ms: number): {
token: CancellationToken;
cancel: (reason?: any) => void;
};
/**
* Create a {CancellationToken} that is cancelled when all of the given tokens are cancelled.
*
* This is like {Promise<T>.all} for {CancellationToken}s.
*/
static all(...tokens: CancellationToken[]): CancellationToken;
/**
* Create a {CancellationToken} that is cancelled when at least one of the given tokens is cancelled.
*
* This is like {Promise<T>.race} for {CancellationToken}s.
*/
static race(...tokens: CancellationToken[]): CancellationToken;
}
declare namespace CancellationToken {
/**
* The error that is thrown when a {CancellationToken} has been cancelled and a
* consumer of the token calls {CancellationToken.throwIfCancelled} on it.
*/
class CancellationError extends Error {
/**
* The reason why the token was cancelled.
*/
readonly reason: any;
constructor(
/**
* The reason why the token was cancelled.
*/
reason: any);
}
}
export default CancellationToken;