@newdash/newdash
Version:
javascript/typescript utility library
44 lines (43 loc) • 1.37 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeout = void 0;
const assert_1 = require("../assert");
const defineFunctionName_1 = __importDefault(require("../functional/defineFunctionName"));
const timeout_1 = require("../timeout");
/**
* wrap an async function with timeout
*
* @since 5.15.0
* @category Async
*
* @param runner async runner please, otherwise the `timeout` is not meaningful
* @param timeout timeout threshold in milliseconds, default value is 60 seconds
*
* @throws {TimeoutError}
*
* @example
*
* ```ts
* const f = timeout(async() => {}, 1000)
* // f() will throw error if the result is not resolved in one second
* ```
*
*/
function timeout(runner, timeout = 60 * 1000) {
(0, assert_1.mustProvide)(runner, "runner", "function");
(0, assert_1.mustProvide)(timeout, "timeout", "number");
const func = (...args) => (0, timeout_1.createTimeoutPromise)(async (resolve, reject) => {
try {
resolve(await runner(...args));
}
catch (error) {
reject(error);
}
}, timeout);
return (0, defineFunctionName_1.default)(func, runner.name);
}
exports.timeout = timeout;
exports.default = timeout;