From 0cafd1d2cb51324379d8875e53083c1825314e5f Mon Sep 17 00:00:00 2001 From: Bryan Ingle Date: Sun, 13 Aug 2023 14:08:59 -0600 Subject: [PATCH] Invoke `clearTimeout` if approriate inside `promise.timeout` function --- .releases/4.29.1.md | 3 +++ lang/promise.js | 33 ++++++++++++++++++++++++++------- 2 files changed, 29 insertions(+), 7 deletions(-) create mode 100644 .releases/4.29.1.md diff --git a/.releases/4.29.1.md b/.releases/4.29.1.md new file mode 100644 index 0000000..bb7eca6 --- /dev/null +++ b/.releases/4.29.1.md @@ -0,0 +1,3 @@ +**Bug Fixes** + +* Fixed issue with `promise.timeout` function. \ No newline at end of file diff --git a/lang/promise.js b/lang/promise.js index 199e3e8..c5b3fa9 100644 --- a/lang/promise.js +++ b/lang/promise.js @@ -32,13 +32,32 @@ module.exports = (() => { return Promise.reject('Unable to configure promise timeout, the "milliseconds" argument must be positive'); } - return Promise.race([ - promise, this.build((resolveCallback, rejectCallback) => { - setTimeout(() => { - rejectCallback(description || `Promise timed out after ${milliseconds} milliseconds`); - }, milliseconds); - }) - ]); + let timeoutToken = null; + + const timeoutPromise = this.build((resolveCallback, rejectCallback) => { + timeoutToken = setTimeout(() => { + rejectCallback(description || `Promise timed out after ${milliseconds} milliseconds`); + }, milliseconds); + }); + + const userPromise = Promise.resolve() + .then(() => { + return promise; + }).then((result) => { + if (timeoutToken !== null) { + clearTimeout(timeoutToken); + } + + return result; + }).catch((e) => { + if (timeoutToken !== null) { + clearTimeout(timeoutToken); + } + + return Promise.reject(e); + }); + + return Promise.race([ userPromise, timeoutPromise ]); }); },