@ayonli/jsext
Version:
A JavaScript extension package for building strong and modern applications.
221 lines (220 loc) • 6.72 kB
TypeScript
/**
* Functions for async/promise context handling.
* @module
*/
/** A promise that can be resolved or rejected manually. */
export type AsyncTask<T> = Promise<T> & {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
};
/**
* Creates a promise that can be resolved or rejected manually.
*
* This function is like `Promise.withResolvers` but less verbose.
*
* @example
* ```ts
* import { asyncTask } from "@ayonli/jsext/async";
*
* const task = asyncTask<number>();
*
* setTimeout(() => task.resolve(42), 1000);
*
* const result = await task;
* console.log(result); // 42
* ```
*/
export declare function asyncTask<T>(): AsyncTask<T>;
/**
* Wraps an async iterable object with an abort signal.
*
* @example
* ```ts
* import { abortable, sleep } from "@ayonli/jsext/async";
*
* async function* generate() {
* yield "Hello";
* await sleep(1000);
* yield "World";
* }
*
* const iterator = generate();
* const controller = new AbortController();
*
* setTimeout(() => controller.abort(), 100);
*
* // prints "Hello" and throws AbortError after 100ms
* for await (const value of abortable(iterator, controller.signal)) {
* console.log(value); // "Hello"
* }
* ```
*/
export declare function abortable<T>(task: AsyncIterable<T>, signal: AbortSignal): AsyncIterable<T>;
/**
* 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.
*
* @example
* ```ts
* import { abortable, sleep } from "@ayonli/jsext/async";
*
* const task = sleep(1000);
* const controller = new AbortController();
*
* setTimeout(() => controller.abort(), 100);
*
* await abortable(task, controller.signal); // throws AbortError after 100ms
* ```
*/
export declare function abortable<T>(task: PromiseLike<T>, signal: AbortSignal): Promise<T>;
/**
* Try to resolve a promise with a timeout limit.
*
* @example
* ```ts
* import { timeout, sleep } from "@ayonli/jsext/async";
*
* const task = sleep(1000);
*
* await timeout(task, 500); // throws TimeoutError after 500ms
* ```
*/
export declare function timeout<T>(task: PromiseLike<T>, ms: number): Promise<T>;
/**
* Resolves a promise only after the given duration.
*
* @example
* ```ts
* import { after } from "@ayonli/jsext/async";
*
* const task = fetch("https://example.com")
* const res = await after(task, 1000);
*
* console.log(res); // the response will not be printed unless 1 second has passed
* ```
*/
export declare function after<T>(task: PromiseLike<T>, ms: number): Promise<T>;
/**
* Blocks the context for a given duration.
*
* @example
* ```ts
* import { sleep } from "@ayonli/jsext/async";
*
* console.log("Hello");
*
* await sleep(1000);
* console.log("World"); // "World" will be printed after 1 second
* ```
*/
export declare function sleep(ms: number): Promise<void>;
/**
* Blocks the current routine 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 check continues.
*
* This functions returns the same result as the test function when passed.
*
* @example
* ```ts
* import { until } from "@ayonli/jsext/async";
*
* // wait for the header element to be present in the DOM
* const ele = await until(() => document.querySelector("header"));
* ```
*/
export declare function 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.
*
* @param tasks An array of promises or functions that return promises.
* @param signal A parent abort signal, if provided and aborted before any task
* completes, the function will reject immediately with the abort reason and
* cancel all tasks.
*
* @example
* ```ts
* // fetch example
* import { select } from "@ayonli/jsext/async";
*
* const res = await select([
* signal => fetch("https://example.com", { signal }),
* signal => fetch("https://example.org", { signal }),
* fetch("https://example.net"), // This task cannot actually be aborted, but ignored
* ]);
*
* console.log(res); // the response from the first completed fetch
* ```
*
* @example
* ```ts
* // with parent signal
* import { select } from "@ayonli/jsext/async";
*
* const signal = AbortSignal.timeout(1000);
*
* try {
* const res = await select([
* signal => fetch("https://example.com", { signal }),
* signal => fetch("https://example.org", { signal }),
* ], signal);
* } catch (err) {
* if ((err as Error).name === "TimeoutError") {
* console.error(err); // Error: signal timed out
* } else {
* throw err;
* }
* }
* ```
*/
export declare function select<T>(tasks: (PromiseLike<T> | ((signal: AbortSignal) => PromiseLike<T>))[], signal?: AbortSignal | undefined): Promise<T>;
/**
* Options for {@link abortWith}.
*
* NOTE: Must provide a `parent` signal or a `timeout` value, or both.
*/
export interface AbortWithOptions {
/**
* The parent signal to be linked with the new abort signal. If the parent
* signal is aborted, the new signal will be aborted with the same reason.
*/
parent?: AbortSignal;
/**
* If provided, the abort signal will be automatically aborted after the
* given duration (in milliseconds) if it is not already aborted.
*/
timeout?: number;
}
/**
* Creates a new abort controller with a `parent` signal, the new abort signal
* will be aborted if the controller's `abort` method is called or when the
* parent signal is aborted, whichever happens first.
*
* @example
* ```ts
* import { abortWith } from "@ayonli/jsext/async";
*
* const parent = new AbortController();
* const child1 = abortWith(parent.signal);
* const child2 = abortWith(parent.signal);
*
* child1.abort();
*
* console.assert(child1.signal.aborted);
* console.assert(!parent.signal.aborted);
*
* parent.abort();
*
* console.assert(child2.signal.aborted);
* console.assert(child2.signal.reason === parent.signal.reason);
* ```
*/
export declare function abortWith(parent: AbortSignal, options?: Omit<AbortWithOptions, "parent">): AbortController;
export declare function abortWith(options: AbortWithOptions): AbortController;