Skip to content

Commit

Permalink
fix(utils): stop immediately when retry limited
Browse files Browse the repository at this point in the history
  • Loading branch information
homura committed Nov 29, 2023
1 parent ddb4d5e commit 03303f6
Showing 1 changed file with 34 additions and 15 deletions.
49 changes: 34 additions & 15 deletions packages/utils/src/async/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,22 @@ export function timeout<T>(
typeof options === "number" ? options : options.milliseconds ?? 1000;
const message = typeof options === "number" ? undefined : options.message;

const timeoutPromise = delay(milliseconds).then(() =>
Promise.reject(
message instanceof Error ? message : createTimeoutError(message)
)
);
return new Promise((resolve, reject) => {
const timeoutTask = setTimeout(() => {
reject(message instanceof Error ? message : createTimeoutError(message));
}, milliseconds);

return race<T>([promise, timeoutPromise]);
promise.then(
(value) => {
clearTimeout(timeoutTask);
resolve(value);
},
(error) => {
clearTimeout(timeoutTask);
reject(error);
}
);
});
}

export interface RetryOptions {
Expand All @@ -73,20 +82,30 @@ export function retry<T>(
delay: delayMs = 0,
} = options;

let lastErr: unknown;
let times = 0;
let currentRetryTimes = 0;

const retryPromise = new Promise<T>((resolve, reject) => {
function retryRun() {
times++;
if (times > retries) {
reject(lastErr);
function handleError(err: unknown) {
currentRetryTimes++;

if (currentRetryTimes >= retries) {
reject(err);
return;
}
Promise.resolve(run()).then(resolve, (e) => {
lastErr = e;

if (delayMs) {
delay(delayMs).then(retryRun);
});
} else {
retryRun();
}
}

function retryRun() {
try {
Promise.resolve(run()).then(resolve, handleError);
} catch (err) {
handleError(err);
}

Check warning on line 108 in packages/utils/src/async/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/utils/src/async/index.ts#L107-L108

Added lines #L107 - L108 were not covered by tests
}

retryRun();
Expand Down

0 comments on commit 03303f6

Please sign in to comment.