@ayonli/jsext
Version:
A JavaScript extension package for building strong and modern applications.
47 lines (44 loc) • 2.02 kB
text/typescript
import { abortable, after, sleep, timeout, until, select } from "../async.ts";
declare global {
interface PromiseConstructor {
/**
* Try to resolve a promise with an abort signal.
*
* **NOTE:** This function does not cancel the task itself, it only prematurely
* breaks the current routine when the signal is aborted. In order to support
* cancellation, the task must be designed to handle the abort signal itself.
*
* @deprecated This signature is confusing and doesn't actually cancel the task,
* use {@link select} instead.
*/
abortable<T>(value: PromiseLike<T>, signal: AbortSignal): Promise<T>;
/** Try to resolve a promise with a timeout limit. */
timeout<T>(value: PromiseLike<T>, ms: number): Promise<T>;
/** Resolves a promise only after the given duration. */
after<T>(value: PromiseLike<T>, ms: number): Promise<T>;
/** Blocks the context for a given duration. */
sleep(ms: number): Promise<void>;
/**
* Blocks the context until the test returns a truthy value, which is not `false`,
* `null` or `undefined`. If the test throws an error, it will be treated as a
* falsy value and the loop continues.
*
* This functions returns the same result as the test function when passed.
*/
until<T>(test: () => T | PromiseLike<T>): Promise<T extends false | null | undefined ? never : T>;
/**
* Runs multiple tasks concurrently and returns the result of the first task that
* completes. The rest of the tasks will be aborted.
*/
select<T>(
tasks: (PromiseLike<T> | ((signal: AbortSignal) => PromiseLike<T>))[],
signal?: AbortSignal | undefined
): Promise<T>;
}
}
Promise.abortable = abortable;
Promise.timeout = timeout;
Promise.after = after;
Promise.sleep = sleep;
Promise.until = until;
Promise.select = select;