UNPKG

@daisugi/kintsugi

Version:

Kintsugi is a set of utilities to help build a fault tolerant services.

22 lines 960 B
import { Result } from '@daisugi/anzen'; import { Ayamari } from '@daisugi/ayamari'; const { errFn } = new Ayamari(); const defaultMaxTimeMs = 600; const timeoutErr = Result.failure(errFn.Timeout('Operation timed out.')); export function withTimeout(fn, opts = {}) { const maxTimeMs = opts.maxTimeMs || defaultMaxTimeMs; return async function (...args) { const promise = fn.apply(this, args); const timeout = new Promise((resolve) => { const timeoutId = setTimeout(() => { resolve(timeoutErr); }, maxTimeMs); //This will handle the promise (and makes possible unhandled-rejection warnings away) to avoid breaking on errors, but you should still handle this promise! promise .catch(() => { }) .then(() => clearTimeout(timeoutId)); }); return Promise.race([timeout, promise]); }; } //# sourceMappingURL=with_timeout.js.map