Skip to content

Commit

Permalink
create timeout promise function
Browse files Browse the repository at this point in the history
  • Loading branch information
rjawesome committed Jun 25, 2024
1 parent 84708cf commit 6f73991
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,27 @@ export function cartesian(a: number[][]): number[][] {
}
return o;
}

export class TimeoutError extends Error {
constructor(message: string) {
super(message);
this.name = "TimeoutError";

Check warning on line 56 in src/misc.ts

View check run for this annotation

Codecov / codecov/patch

src/misc.ts#L55-L56

Added lines #L55 - L56 were not covered by tests
}
}

// Do not use on the same promise multiple times
export function timeoutPromise<T>(promise: Promise<T>, timeout: number): Promise<T> {
let reject = (_: any) => {};
let resolve = (_: T) => {};
const cancel = setTimeout(() => {
reject(new TimeoutError(`Promise exceeded timeout of ${timeout/1000} seconds.`));

Check warning on line 65 in src/misc.ts

View check run for this annotation

Codecov / codecov/patch

src/misc.ts#L62-L65

Added lines #L62 - L65 were not covered by tests
}, timeout);
promise
.then(result => resolve(result))
.catch(error => reject(error))
.finally(() => clearTimeout(cancel));
return new Promise<T>((newResolve, newReject) => {
resolve = newResolve;
reject = newReject;

Check warning on line 73 in src/misc.ts

View check run for this annotation

Codecov / codecov/patch

src/misc.ts#L67-L73

Added lines #L67 - L73 were not covered by tests
});
}

0 comments on commit 6f73991

Please sign in to comment.