Clear setTimeout when fetch wins the race
Prevents the timer callback from firing unnecessarily after a successful fetch response.
This commit is contained in:
@@ -17,11 +17,15 @@ const HEALTH_CHECK_TIMEOUT_MS = getTimeout(HOOK_TIMEOUTS.HEALTH_CHECK);
|
|||||||
* The orphaned fetch is harmless since the process exits shortly after.
|
* The orphaned fetch is harmless since the process exits shortly after.
|
||||||
*/
|
*/
|
||||||
export function fetchWithTimeout(url: string, init: RequestInit = {}, timeoutMs: number): Promise<Response> {
|
export function fetchWithTimeout(url: string, init: RequestInit = {}, timeoutMs: number): Promise<Response> {
|
||||||
|
let timeoutId: ReturnType<typeof setTimeout>;
|
||||||
return Promise.race([
|
return Promise.race([
|
||||||
fetch(url, init),
|
fetch(url, init).then(response => {
|
||||||
new Promise<never>((_, reject) =>
|
clearTimeout(timeoutId);
|
||||||
setTimeout(() => reject(new Error(`Request timed out after ${timeoutMs}ms`)), timeoutMs)
|
return response;
|
||||||
),
|
}),
|
||||||
|
new Promise<never>((_, reject) => {
|
||||||
|
timeoutId = setTimeout(() => reject(new Error(`Request timed out after ${timeoutMs}ms`)), timeoutMs);
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user