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