UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

50 lines (49 loc) 1.84 kB
import type { ErrorData } from '../error/error.model.js'; import { TimeoutError } from '../error/error.util.js'; import type { AnyAsyncFunction, NumberOfMilliseconds } from '../types.js'; export interface PTimeoutOptions { /** * Timeout in milliseconds. * * If 0 is passed - the function would be executed right away, with no timeout. */ timeout: NumberOfMilliseconds; /** * If set - will be included in the error message. * Can be used to identify the place in the code that failed. */ name?: string; /** * If provided - will be called INSTEAD of throwing an error. * Can be used to thrown a custom error OR resolve a promise without throwing. * * err (which is TimeoutError) is passed as an argument for convenience, so it can * be logged or such. You don't have to consume it in any way though. */ onTimeout?: (err: TimeoutError) => any; /** * If passed - fakeError.stack will be used as a stacktrace. * This is to "keep stacktrace" when pTimeout is called from another * function (like pRetry). */ fakeError?: Error; /** * Will be merged with `err.data` object. */ errorData?: ErrorData; } /** * Decorates a Function with a timeout. * Returns a decorated Function. * * Throws an Error if the Function is not resolved in a certain time. * If the Function rejects - passes this rejection further. */ export declare function pTimeoutFn<T extends AnyAsyncFunction>(fn: T, opt: PTimeoutOptions): T; /** * Decorates a Function with a timeout and immediately calls it. * * Throws an Error if the Function is not resolved in a certain time. * If the Function rejects - passes this rejection further. */ export declare function pTimeout<T>(fn: AnyAsyncFunction<T>, opt: PTimeoutOptions): Promise<T>;