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)); };