Skip to content

Commit 00bc234

Browse files
refactor: improve retry logic with a for loop
This commit refactors the retry logic to use a `for` loop, which is cleaner and more concise than the previous `while` loop implementation. The exit conditions are now combined into a single check, improving readability and maintainability. This change also addresses the original issue of stack overflows and memory leaks caused by the recursive implementation.
1 parent 5f94b6c commit 00bc234

1 file changed

Lines changed: 15 additions & 9 deletions

File tree

pages/index.tsx

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -147,22 +147,28 @@ const Index = () => {
147147
isCutBorders ? "cutBorders" : "",
148148
anilistFilter ? `anilistID=${anilistFilter}` : "",
149149
].join("&");
150-
const res = await fetch(`${NEXT_PUBLIC_API_ENDPOINT}/search?${queryString}`, {
151-
method: "POST",
152-
body: formData,
153-
});
150+
let res;
151+
for (let retries = 5; retries > 0; retries--) {
152+
res = await fetch(`${NEXT_PUBLIC_API_ENDPOINT}/search?${queryString}`, {
153+
method: "POST",
154+
body: formData,
155+
});
156+
if (res.status !== 503 || retries === 1) {
157+
break;
158+
}
159+
for (let i = 5; i > 0; i--) {
160+
setMessageText(`Server is busy, retrying in ${i}s`);
161+
await new Promise((resolve) => setTimeout(resolve, 1000));
162+
}
163+
}
154164
setIsSearching(false);
155165

156166
if (res.status === 429) {
157167
setMessageText("You searched too many times, please try again later.");
158168
return;
159169
}
160170
if (res.status === 503) {
161-
for (let i = 5; i > 0; i--) {
162-
setMessageText(`Server is busy, retrying in ${i}s`);
163-
await new Promise((resolve) => setTimeout(resolve, 1000));
164-
}
165-
search(imageBlob);
171+
setMessageText("Server is busy, please try again later.");
166172
return;
167173
}
168174
if (res.status >= 400) {

0 commit comments

Comments
 (0)