Restructure fetchWithTimeout to clear timer on all paths

Replace Promise.race with new Promise wrapper so timeoutId is assigned
as const before fetch starts. Timer is now cleared on both fetch success
and fetch rejection, not just success.
This commit is contained in:
Rod Boev
2026-02-05 10:38:11 -05:00
committed by Alex Newman
parent 1ac35b5d56
commit 64dc50f3fb
+10 -10
View File
@@ -17,16 +17,16 @@ const HEALTH_CHECK_TIMEOUT_MS = getTimeout(HOOK_TIMEOUTS.HEALTH_CHECK);
* The orphaned fetch is harmless since the process exits shortly after.
*/
export function fetchWithTimeout(url: string, init: RequestInit = {}, timeoutMs: number): Promise<Response> {
let timeoutId: ReturnType<typeof setTimeout>;
return Promise.race([
fetch(url, init).then(response => {
clearTimeout(timeoutId);
return response;
}),
new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error(`Request timed out after ${timeoutMs}ms`)), timeoutMs);
}),
]);
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(
() => reject(new Error(`Request timed out after ${timeoutMs}ms`)),
timeoutMs
);
fetch(url, init).then(
response => { clearTimeout(timeoutId); resolve(response); },
err => { clearTimeout(timeoutId); reject(err); }
);
});
}
// Cache to avoid repeated settings file reads