UNPKG

obsidian-dev-utils

Version:

This is the collection of useful functions that you can use for your Obsidian plugin development

184 lines (183 loc) 8.43 kB
/** * @packageDocumentation * * Contains utility functions for asynchronous operations. */ import type { Promisable } from 'type-fest'; /** * A type representing a function that resolves a {@link Promise}. * * @typeParam T - The type of the value. */ export type PromiseResolve<T> = undefined extends T ? (value?: PromiseLike<T> | T) => void : (value: PromiseLike<T> | T) => void; /** * A constant representing an infinite timeout. */ export declare const INFINITE_TIMEOUT: number; /** * Options for configuring the retry behavior. */ export interface RetryOptions { /** * The abort signal to cancel the retry operation. */ abortSignal?: AbortSignal; /** * The delay in milliseconds between retry attempts. */ retryDelayInMilliseconds?: number; /** * Whether to retry the function on error. */ shouldRetryOnError?: boolean; /** * The maximum time in milliseconds to wait before giving up on retrying. */ timeoutInMilliseconds?: number; } /** * A marker interface to indicate that an error should terminate retry logic. */ export interface TerminateRetry { /** * A marker property to indicate that an error should terminate retry logic. */ __terminateRetry: true; } /** * Adds an error handler to a {@link Promise} that catches any errors and emits an async error event. * * @param asyncFn - The asynchronous function to add an error handler to. * @returns A {@link Promise} that resolves when the asynchronous function completes or emits async error event. */ export declare function addErrorHandler(asyncFn: () => Promise<unknown>): Promise<void>; /** * Filters an array asynchronously, keeping only the elements that satisfy the provided predicate function. * * @typeParam T - The type of elements in the input array. * @param arr - The array to filter. * @param predicate - The predicate function to test each element. * @returns A {@link Promise} that resolves with an array of elements that satisfy the predicate function. */ export declare function asyncFilter<T>(arr: T[], predicate: (value: T, index: number, array: T[]) => Promisable<boolean>): Promise<T[]>; /** * Maps over an array asynchronously, applying the provided callback function to each element, and then flattens the results into a single array. * * @typeParam T - The type of elements in the input array. * @typeParam U - The type of elements in the output array. * @param arr - The array to map over and flatten. * @param callback - The callback function to apply to each element. * @returns A {@link Promise} that resolves with a flattened array of the results of the callback function. */ export declare function asyncFlatMap<T, U>(arr: T[], callback: (value: T, index: number, array: T[]) => Promisable<U[]>): Promise<U[]>; /** * Maps over an array asynchronously, applying the provided callback function to each element. * * @typeParam T - The type of elements in the input array. * @typeParam U - The type of elements in the output array. * @param arr - The array to map over. * @param callback - The callback function to apply to each element. * @returns A {@link Promise} that resolves with an array of the results of the callback function. */ export declare function asyncMap<T, U>(arr: T[], callback: (value: T, index: number, array: T[]) => Promisable<U>): Promise<U[]>; /** * Converts an asynchronous function to a synchronous one by automatically handling the Promise rejection. * * @typeParam Args - The types of the arguments the function accepts. * @param asyncFunc - The asynchronous function to convert. * @returns A function that wraps the asynchronous function in a synchronous interface. */ export declare function convertAsyncToSync<Args extends unknown[]>(asyncFunc: (...args: Args) => Promise<unknown>): (...args: Args) => void; /** * Converts a synchronous function to an asynchronous one by wrapping it in a {@link Promise}. * * @typeParam Args - The types of the arguments the function accepts. * @typeParam Result - The type of the function's return value. * @param syncFn - The synchronous function to convert. * @returns A function that wraps the synchronous function in an asynchronous interface. */ export declare function convertSyncToAsync<Args extends unknown[], Result>(syncFn: (...args: Args) => Result): (...args: Args) => Promise<Result>; /** * Ignores an error that is thrown by an asynchronous function. * * @param promise - The promise to ignore the error of. * @param fallbackValue - Always `undefined`. * @returns A {@link Promise} that resolves when the asynchronous function completes or fails. */ export declare function ignoreError(promise: Promise<unknown>, fallbackValue?: undefined): Promise<void>; /** * Invokes a {@link Promise} and safely handles any errors by catching them and emitting an async error event. * * @param asyncFn - The asynchronous function to invoke safely. */ export declare function invokeAsyncSafely(asyncFn: () => Promise<unknown>): void; /** * Invokes an asynchronous function after a delay. * * @param asyncFn - The asynchronous function to invoke. * @param delayInMilliseconds - The delay in milliseconds. */ export declare function invokeAsyncSafelyAfterDelay(asyncFn: () => Promisable<unknown>, delayInMilliseconds?: number): void; /** * Marks an error to terminate retry logic. * * @param error - The error to mark to terminate retry logic. * @returns An error that should terminate retry logic. */ export declare function marksAsTerminateRetry<TError extends Error>(error: TError): TerminateRetry & TError; /** * Gets the next request animation frame. * * @returns A promise that resolves when the next request animation frame is available. */ export declare function requestAnimationFrameAsync(): Promise<void>; /** * Retries the provided function until it returns true or the timeout is reached. * * @param fn - The function to retry. * @param retryOptions - Optional parameters to configure the retry behavior. * @param stackTrace - Optional stack trace. * @returns A {@link Promise} that resolves when the function returns true or rejects when the timeout is reached. */ export declare function retryWithTimeout(fn: () => Promisable<boolean>, retryOptions?: RetryOptions, stackTrace?: string): Promise<void>; /** * Executes a function with a timeout. If the function does not complete within the specified time, it is considered to have timed out. * * If `DEBUG=obsidian-dev-utils:Async:runWithTimeout` is set, the execution is not terminated after the timeout and the function is allowed to run indefinitely. * * @typeParam R - The type of the result from the asynchronous function. * @param timeoutInMilliseconds - The maximum time to wait in milliseconds. * @param fn - The function to execute. * @param context - The context of the function. * @returns A {@link Promise} that resolves with the result of the asynchronous function or rejects if it times out. */ export declare function runWithTimeout<R>(timeoutInMilliseconds: number, fn: () => Promisable<R>, context?: unknown): Promise<R>; /** * Delays execution for a specified number of milliseconds. * * @param milliseconds - The time to wait in milliseconds. * @returns A {@link Promise} that resolves after the specified delay. */ export declare function sleep(milliseconds: number): Promise<void>; /** * Returns a {@link Promise} that rejects when the abort signal is aborted. * * @param abortSignal - The abort signal to listen to. * @returns A {@link Promise} that rejects when the abort signal is aborted. */ export declare function throwOnAbort(abortSignal: AbortSignal): Promise<void>; /** * Returns a {@link Promise} that rejects after the specified timeout period. * * @param timeoutInMilliseconds - The timeout period in milliseconds. * @returns A {@link Promise} that always rejects with a timeout error. */ export declare function timeout(timeoutInMilliseconds: number): Promise<never>; /** * Converts an AsyncIterableIterator to an array by consuming all its elements. * * @typeParam T - The type of elements produced by the AsyncIterableIterator. * @param iter - The AsyncIterableIterator to convert. * @returns A {@link Promise} that resolves with an array of all the elements in the AsyncIterableIterator. */ export declare function toArray<T>(iter: AsyncIterableIterator<T>): Promise<T[]>;