New timeout mechanics with better error stack

This commit is contained in:
Daniel Lugo 2021-07-23 15:04:06 -04:00
parent ae5cd44b74
commit 163cd033e5

View file

@ -25,50 +25,54 @@ const delay = ms => new Promise(res => setTimeout(res, ms))
const mySecret = () => Promise.resolve(require('../../Mediator').getMySecret()) const mySecret = () => Promise.resolve(require('../../Mediator').getMySecret())
/** /**
* @template T * Just a pointer.
* @param {Promise<T>} promise
* @returns {Promise<T>}
*/ */
const timeout5 = promise => { const TIMEOUT_PTR = {}
/**
* @param {number} ms Milliseconds
* @returns {<T>(promise: Promise<T>) => Promise<T>}
*/
const timeout = ms => async promise => {
/** @type {NodeJS.Timeout} */ /** @type {NodeJS.Timeout} */
// @ts-ignore // @ts-ignore
let timeoutID let timeoutID
return Promise.race([
const result = await Promise.race([
promise.then(v => { promise.then(v => {
clearTimeout(timeoutID) clearTimeout(timeoutID)
return v return v
}), }),
new Promise((_, rej) => { CommonUtils.makePromise(res => {
timeoutID = setTimeout(() => { timeoutID = setTimeout(() => {
rej(new Error(Constants.ErrorCode.TIMEOUT_ERR)) clearTimeout(timeoutID)
}, 5000) res(TIMEOUT_PTR)
}, ms)
}) })
]) ])
if (result === TIMEOUT_PTR) {
throw new Error(Constants.TIMEOUT_ERR)
}
return result
} }
/** /**
* @template T * Time outs at 10 seconds.
* @param {Promise<T>} promise
* @returns {Promise<T>}
*/ */
const timeout2 = promise => { const timeout10 = timeout(10)
/** @type {NodeJS.Timeout} */
// @ts-ignore
let timeoutID
return Promise.race([
promise.then(v => {
clearTimeout(timeoutID)
return v
}),
new Promise((_, rej) => { /**
timeoutID = setTimeout(() => { * Time outs at 5 seconds.
rej(new Error(Constants.ErrorCode.TIMEOUT_ERR)) */
}, 2000) const timeout5 = timeout(5)
})
]) /**
} * Time outs at 2 seconds.
*/
const timeout2 = timeout(2)
/** /**
* @template T * @template T