UNPKG

@lakutata/core

Version:

Lakutata Framework Core

27 lines (26 loc) 918 B
import pTimeout from 'p-timeout' import {Exception} from '../base/abstracts/Exception' import {TimeoutException} from '../exceptions/TimeoutException' /** * 方法运行时间限定超时函数 * @param {Promise<T>} p * @param {number} milliseconds * @param {(() => (Promise<T> | T)) | string | Exception} messageOrFallback * @returns {Promise<T>} */ export async function timeout<T>(p: Promise<T>, milliseconds: number, messageOrFallback?: (() => T | Promise<T>) | string | Exception): Promise<T> { return pTimeout(p, milliseconds, async () => { if (messageOrFallback) { switch (typeof messageOrFallback) { case 'function': return (await messageOrFallback()) as any case 'string': throw new TimeoutException(messageOrFallback) case 'object': throw messageOrFallback } } else { throw new TimeoutException(`Promise timed out after ${milliseconds} milliseconds`) } }) }