Skip to content

Commit

Permalink
Merge pull request #4 from biothings/parallel-creative
Browse files Browse the repository at this point in the history
create timeout promise function
  • Loading branch information
tokebe authored Oct 11, 2024
2 parents 581f71b + 4889b25 commit 9e4d04a
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/misc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,26 @@ export function cartesian(a: number[][]): number[][] {
return o;
}

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

// 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.`));
}, timeout);
promise
.then(result => resolve(result))
.catch(error => reject(error))
.finally(() => clearTimeout(cancel));
return new Promise<T>((newResolve, newReject) => {
resolve = newResolve;
reject = newReject;
});
}

0 comments on commit 9e4d04a

Please sign in to comment.