From 163cd033e53491a90462e65fe86265c5bbac2581 Mon Sep 17 00:00:00 2001 From: Daniel Lugo Date: Fri, 23 Jul 2021 15:04:06 -0400 Subject: [PATCH] New timeout mechanics with better error stack --- services/gunDB/contact-api/utils/index.js | 58 ++++++++++++----------- 1 file changed, 31 insertions(+), 27 deletions(-) diff --git a/services/gunDB/contact-api/utils/index.js b/services/gunDB/contact-api/utils/index.js index 619b04d2..7022e221 100644 --- a/services/gunDB/contact-api/utils/index.js +++ b/services/gunDB/contact-api/utils/index.js @@ -25,50 +25,54 @@ const delay = ms => new Promise(res => setTimeout(res, ms)) const mySecret = () => Promise.resolve(require('../../Mediator').getMySecret()) /** - * @template T - * @param {Promise} promise - * @returns {Promise} + * Just a pointer. */ -const timeout5 = promise => { +const TIMEOUT_PTR = {} + +/** + * @param {number} ms Milliseconds + * @returns {(promise: Promise) => Promise} + */ +const timeout = ms => async promise => { /** @type {NodeJS.Timeout} */ // @ts-ignore let timeoutID - return Promise.race([ + + const result = await Promise.race([ promise.then(v => { clearTimeout(timeoutID) return v }), - new Promise((_, rej) => { + CommonUtils.makePromise(res => { timeoutID = setTimeout(() => { - rej(new Error(Constants.ErrorCode.TIMEOUT_ERR)) - }, 5000) + clearTimeout(timeoutID) + res(TIMEOUT_PTR) + }, ms) }) ]) + + if (result === TIMEOUT_PTR) { + throw new Error(Constants.TIMEOUT_ERR) + } + + return result } /** - * @template T - * @param {Promise} promise - * @returns {Promise} + * Time outs at 10 seconds. */ -const timeout2 = promise => { - /** @type {NodeJS.Timeout} */ - // @ts-ignore - let timeoutID - return Promise.race([ - promise.then(v => { - clearTimeout(timeoutID) - return v - }), +const timeout10 = timeout(10) - new Promise((_, rej) => { - timeoutID = setTimeout(() => { - rej(new Error(Constants.ErrorCode.TIMEOUT_ERR)) - }, 2000) - }) - ]) -} +/** + * Time outs at 5 seconds. + */ +const timeout5 = timeout(5) + +/** + * Time outs at 2 seconds. + */ +const timeout2 = timeout(2) /** * @template T