import { AsyncErrorCallback, RetryWorker } from "../interfaces"; import { once } from "../common"; /** * This method executes a function once, and then retry executing it N times * while it still failing. * * It means the function will be executed at least 1 time and at most N+1 * times. */ export function retry( times: number, mainBody: RetryWorker, final?: AsyncErrorCallback ): void { let lastError: E; let loop = function(i: number): void { if (i > times) { final && final(lastError); return; } mainBody(once(function(err?: E, quit?: boolean): void { if (err !== null && err !== undefined) { if (quit) { final && final(err); } else { lastError = err; loop(i + 1); } } else { final && final(); } }), i); }; loop(0); }