@daisugi/kintsugi
Version:
Kintsugi is a set of utilities to help build a fault tolerant services.
25 lines • 1.09 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.withTimeout = withTimeout;
const anzen_1 = require("@daisugi/anzen");
const ayamari_1 = require("@daisugi/ayamari");
const { errFn } = new ayamari_1.Ayamari();
const defaultMaxTimeMs = 600;
const timeoutErr = anzen_1.Result.failure(errFn.Timeout('Operation timed out.'));
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