UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

86 lines (85 loc) 2.68 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.retry = void 0; const assert_1 = require("./assert"); const defineFunctionName_1 = __importDefault(require("./functional/defineFunctionName")); const isAsyncFunction_1 = __importDefault(require("./isAsyncFunction")); const sleep_1 = __importDefault(require("./sleep")); /** * @ignore * @internal * @private * @param error * @param ctx */ function errorWithRetry(error, ctx) { if (ctx.retryCount < ctx.maxRetryCount) { ctx.retryCount++; if (ctx.isAsync && ctx.retryAfterMSecond > 0) { return (0, sleep_1.default)(ctx.retryAfterMSecond).then(() => runWithRetryLimit(ctx)); } return runWithRetryLimit(ctx); } throw error; } /** * @ignore * @internal * @private * @param ctx */ function runWithRetryLimit(ctx) { const { runner, args } = ctx; try { const rt = runner(...args); if (rt instanceof Promise) { ctx.isAsync = true; return rt.catch((error) => errorWithRetry(error, ctx)); } return rt; } catch (error) { return errorWithRetry(error, ctx); } } /** * make function retry-able * * e.g. if `maxRetryCount` is 3, it will run 3 times at most (include the first one), and return the final error. * * @since 5.14.0 * @category Async * @param runner async function, return promise * @param maxRetryCount the maximum number of times a runner should retry, default is 3 * @param retryAfterMSecond (async function required, for sync function, this parameter will not be applied) the wait milliseconds before retry, default is zero */ function retry(runner, maxRetryCount = 3, retryAfterMSecond = 0) { (0, assert_1.mustProvide)(runner, "runner", "function"); if (maxRetryCount > 1) { const isAsync = (0, isAsyncFunction_1.default)(runner); const warpRunner = function (...args) { return runWithRetryLimit({ runner, retryCount: 1, args, retryAfterMSecond, maxRetryCount, isAsync }); }; if (isAsync) { return (0, defineFunctionName_1.default)(async function (...args) { return warpRunner(...args); }, runner.name); } else { return (0, defineFunctionName_1.default)(warpRunner, runner.name); } } return runner; } exports.retry = retry; exports.default = retry;