Skip to content

Commit d2aecb4

Browse files
committed
fix: prevent extra iterations occurring on retryOrTimeout
1 parent 06d9405 commit d2aecb4

File tree

2 files changed

+23
-6
lines changed

2 files changed

+23
-6
lines changed

src/api.spec.ts

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -681,8 +681,7 @@ describe("API", () => {
681681
const attempt = () => Promise.resolve([]);
682682

683683
const retryOrTimeoutPromise = retryOrTimeout(attempt, 1000);
684-
// eslint-disable-next-line @typescript-eslint/no-floating-promises
685-
vi.advanceTimersByTimeAsync(2000);
684+
await vi.advanceTimersByTimeAsync(2000);
686685

687686
const result = await retryOrTimeoutPromise;
688687
if (result.success) {
@@ -701,8 +700,7 @@ describe("API", () => {
701700
.mockResolvedValueOnce([]);
702701

703702
const retryOrDiePromise = retryOrTimeout(attempt, 5000);
704-
// eslint-disable-next-line @typescript-eslint/no-floating-promises
705-
vi.advanceTimersByTimeAsync(3000);
703+
await vi.advanceTimersByTimeAsync(3000);
706704

707705
const result = await retryOrDiePromise;
708706
if (!result.success) {
@@ -713,5 +711,25 @@ describe("API", () => {
713711
expect(result.value).toStrictEqual(attemptResult);
714712
expect(attempt).toHaveBeenCalledTimes(3);
715713
});
714+
715+
it("should iterate only once if timed out", async () => {
716+
const attempt = vi.fn(() => Promise.resolve([]));
717+
718+
const retryOrTimeoutPromise = retryOrTimeout(attempt, 1000);
719+
720+
expect(attempt).toHaveBeenCalledOnce();
721+
722+
await vi.advanceTimersByTimeAsync(2000);
723+
724+
const result = await retryOrTimeoutPromise;
725+
726+
if (result.success) {
727+
expect.fail("expected retryOrTimeout to timeout");
728+
}
729+
expect(attempt).toHaveBeenCalledOnce();
730+
731+
expect(result.success).toStrictEqual(false);
732+
expect(result.reason).toStrictEqual("timeout");
733+
});
716734
});
717735
});

src/api.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -269,14 +269,13 @@ export async function retryOrTimeout<T>(
269269
const startTime = Date.now();
270270
let elapsedTime = 0;
271271
while (elapsedTime < timeoutMs) {
272-
elapsedTime = Date.now() - startTime;
273-
274272
const response = await retryFunc();
275273
if (response.length > 0) {
276274
return { success: true, value: response };
277275
}
278276

279277
await sleep(1000);
278+
elapsedTime = Date.now() - startTime;
280279
}
281280

282281
return { success: false, reason: "timeout" };

0 commit comments

Comments
 (0)