Skip to content

Commit

Permalink
Remove duplication (#75)
Browse files Browse the repository at this point in the history
  • Loading branch information
parzhitsky committed Jul 19, 2020
1 parent 26d9e17 commit a196b49
Showing 1 changed file with 37 additions and 40 deletions.
77 changes: 37 additions & 40 deletions src/retryable.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type Action from "./typings/action";
import type Retryer from "./typings/retryer";
import type { Delay } from "./delays";

import assertNatural from "./assert-natural.impl";
Expand Down Expand Up @@ -66,30 +67,36 @@ export default function retryable<Value = unknown>(action: Action<Value>): Promi
}

return new Promise<Value>((resolve, reject) => {
/** @private */
function execute(): void {
action(
resolve,
reject,
// explicitly relying on hoisting here
// eslint-disable-next-line @typescript-eslint/no-use-before-define
retry,
const retry: Retryer = Object.assign(() => {
updateRetryCount();

// arguments below are deprecated,
// left for backwards compatibility
// explicitly relying on hoisting here
// eslint-disable-next-line @typescript-eslint/no-use-before-define
execute();
}, {
count: _retryCount, // temporary

_retryCount,
resetRetryCount.bind(null, false),
);
}
setCount: resetRetryCount.bind(null, true),

function retry(): void {
updateRetryCount();
execute();
}
after(delay: Delay): void {
let msec: number;

if (isNamed(delay))
msec = delays[delay](_retryCount);

else
msec = +delay;

// rough fix: TypeScript doesn't know about Object.defineProperty
retry.count = _retryCount;
assertNonNegative(msec, "retry delay");

_retryTimeoutId = setTimeout(retry, msec);
},

cancel(): void {
if (_retryTimeoutId != null)
clearTimeout(_retryTimeoutId);
},
});

Object.defineProperty(retry, "count", {
get(): number {
Expand All @@ -101,30 +108,20 @@ export default function retryable<Value = unknown>(action: Action<Value>): Promi
},
});

retry.setCount = resetRetryCount.bind(null, true);

function retryAfter(delay: Delay): void {
let msec: number;

if (isNamed(delay))
msec = delays[delay](_retryCount);

else
msec = +delay;

assertNonNegative(msec, "retry delay");
function execute(): void {
action(
resolve,
reject,
retry,

_retryTimeoutId = setTimeout(retry, msec);
}
// arguments below are deprecated,
// left for backwards compatibility

function retryCancel(): void {
if (_retryTimeoutId != null)
clearTimeout(_retryTimeoutId);
_retryCount,
resetRetryCount.bind(null, false),
);
}

retry.after = retryAfter;
retry.cancel = retryCancel;

execute();
});
}

0 comments on commit a196b49

Please sign in to comment.