UNPKG

ox

Version:

Ethereum Standard Library

46 lines 1.46 kB
import * as Errors from '../Errors.js'; /** @internal */ export function withTimeout(fn, options) { const { errorInstance = new TimeoutError(), timeout, signal } = options; // Fast path: no timeout, skip allocating Promise wrapper and AbortController. if (!(timeout > 0)) return fn({ signal: null }); return new Promise((resolve, reject) => { void (async () => { let timeoutId; let timedOut = false; const controller = signal ? new AbortController() : null; try { timeoutId = setTimeout(() => { timedOut = true; if (controller) controller.abort(); else reject(errorInstance); }, timeout); resolve(await fn({ signal: controller?.signal ?? null })); } catch (err) { if (timedOut || err?.name === 'AbortError') reject(errorInstance); else reject(err); } finally { clearTimeout(timeoutId); } })(); }); } /** @internal */ /** * Thrown when an operation times out. * @internal */ export class TimeoutError extends Errors.BaseError { name = 'Promise.TimeoutError'; constructor() { super('Operation timed out.'); } } //# sourceMappingURL=promise.js.map