Skip to content

Commit

Permalink
feat: less leaky timeout implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
FauxFaux committed Dec 5, 2020
1 parent 5222931 commit 015ee4a
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/jest-circus/src/deadlineTimeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ function isUs(line: string): boolean {

async function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
let resolvePromise: { (value: boolean): void } | undefined;
try {
return await Promise.race([
promise,
(async () => {
await new Promise(resolve => {
timeoutId = setTimeout(resolve, ms);
(async (): Promise<never> => {
const firedForReal = await new Promise<boolean>(resolve => {
resolvePromise = resolve;
timeoutId = setTimeout(() => resolve(true), ms);
});
timeoutId = undefined;
if (!firedForReal) {
return undefined as never;
}
const here = new Error(`deadline exceeded (waited here for ${ms}ms)`);
here.stack = here.stack
?.split('\n')
Expand All @@ -38,5 +42,6 @@ async function timeout<T>(promise: Promise<T>, ms: number): Promise<T> {
if (timeoutId) {
clearTimeout(timeoutId);
}
resolvePromise?.(false);
}
}

0 comments on commit 015ee4a

Please sign in to comment.