From 0d7b48e454bd3d2623bc9167305915dcbaa7cbcd Mon Sep 17 00:00:00 2001 From: Livio Brunner Date: Fri, 26 Nov 2021 18:21:20 +0100 Subject: [PATCH] fix(health): open handle when using `pingCheck` in jest environment resolves #1466 --- lib/utils/promise-timeout.ts | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/lib/utils/promise-timeout.ts b/lib/utils/promise-timeout.ts index e5270f7ed..2daf133c3 100644 --- a/lib/utils/promise-timeout.ts +++ b/lib/utils/promise-timeout.ts @@ -16,18 +16,19 @@ export class TimeoutError extends Error {} * * @internal */ -export const promiseTimeout = function( +export const promiseTimeout = function ( ms: number, promise: Promise, ): Promise { - // Create a promise that rejects in milliseconds - let timeout = new Promise((_, reject) => { - let id = setTimeout(() => { - clearTimeout(id); - reject(new TimeoutError('Timed out in ' + ms + 'ms.')); - }, ms); - }); - - // Returns a race between our timeout and the passed in promise - return Promise.race([promise, timeout]); + let timer: NodeJS.Timeout; + return Promise.race([ + promise, + new Promise( + (_, reject) => + (timer = setTimeout( + () => reject(new TimeoutError(`Timed out in ${ms}ms.`)), + ms, + )), + ), + ]).finally(() => clearTimeout(timer)); };