fix: Anify timeout logic running even when fetch resolved
Summary: Test Plan:
This commit is contained in:
27
src/libs/promiseTimeout.ts
Normal file
27
src/libs/promiseTimeout.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export function promiseTimeout<T>(
|
||||
promise: Promise<T>,
|
||||
timeoutMs: number,
|
||||
): Promise<T | null> {
|
||||
let hasPromiseResolved = false;
|
||||
|
||||
return Promise.race([
|
||||
promise.then((value) => {
|
||||
hasPromiseResolved = true;
|
||||
return value;
|
||||
}),
|
||||
new Promise((resolve) => setTimeout(resolve, timeoutMs)).then(() => {
|
||||
if (hasPromiseResolved) {
|
||||
return null;
|
||||
}
|
||||
|
||||
throw new PromiseTimedOutError();
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
export class PromiseTimedOutError extends Error {
|
||||
constructor(message?: string) {
|
||||
super(message ?? "Promise timed out");
|
||||
this.name = "PromiseTimedOutError";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user