diff --git a/lib/hooks/wait-for-connection.js b/lib/hooks/wait-for-connection.js index 78556b0b7f..7ba9c75363 100644 --- a/lib/hooks/wait-for-connection.js +++ b/lib/hooks/wait-for-connection.js @@ -7,6 +7,8 @@ import { useTunnelbroker } from '../tunnelbroker/tunnelbroker-context.js'; import { authoritativeKeyserverID } from '../utils/authoritative-keyserver.js'; import { useSelector } from '../utils/redux-utils.js'; +const WAITING_TIMEOUT = 5 * 1000; // 5 seconds + function useWaitForConnection(): () => Promise { const { socketState } = useTunnelbroker(); @@ -14,9 +16,9 @@ function useWaitForConnection(): () => Promise { connectionSelector(authoritativeKeyserverID()), ); - const resolveConnectionPromisesCallbacks = React.useRef void>>( - [], - ); + const resolveConnectionPromisesCallbacks = React.useRef< + Array<{ +callback: () => void, +timeoutID: TimeoutID }>, + >([]); const isConnectedOrUnreachable = React.useMemo(() => { return ( @@ -27,7 +29,12 @@ function useWaitForConnection(): () => Promise { React.useEffect(() => { if (isConnectedOrUnreachable) { - resolveConnectionPromisesCallbacks.current.forEach(cb => cb()); + resolveConnectionPromisesCallbacks.current.forEach(({ timeoutID }) => + clearTimeout(timeoutID), + ); + resolveConnectionPromisesCallbacks.current.forEach(({ callback }) => + callback(), + ); resolveConnectionPromisesCallbacks.current = []; } }, [isConnectedOrUnreachable]); @@ -36,8 +43,18 @@ function useWaitForConnection(): () => Promise { if (isConnectedOrUnreachable) { return Promise.resolve(); } - return new Promise(resolve => { - resolveConnectionPromisesCallbacks.current.push(resolve); + return new Promise((resolve, reject) => { + const timeoutID = setTimeout(() => { + resolveConnectionPromisesCallbacks.current = + resolveConnectionPromisesCallbacks.current.filter( + ({ callback }) => callback !== resolve, + ); + reject(new Error('Timeout while waiting for connection')); + }, WAITING_TIMEOUT); + resolveConnectionPromisesCallbacks.current.push({ + callback: resolve, + timeoutID, + }); }); }, [isConnectedOrUnreachable]);