From 5c24547ef5215b00333da3e9e7b61a55f222f7f6 Mon Sep 17 00:00:00 2001 From: Michael Telatynski <7t3chguy@gmail.com> Date: Thu, 14 Nov 2019 09:37:26 +0000 Subject: [PATCH] re-add and actually use promise timeout util Signed-off-by: Michael Telatynski <7t3chguy@gmail.com> --- src/components/views/settings/SetIdServer.js | 12 +++++------- src/utils/promise.js | 13 +++++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/components/views/settings/SetIdServer.js b/src/components/views/settings/SetIdServer.js index 126cdc9557..a7a2e01c22 100644 --- a/src/components/views/settings/SetIdServer.js +++ b/src/components/views/settings/SetIdServer.js @@ -26,6 +26,7 @@ import { getThreepidsWithBindStatus } from '../../../boundThreepids'; import IdentityAuthClient from "../../../IdentityAuthClient"; import {abbreviateUrl, unabbreviateUrl} from "../../../utils/UrlUtils"; import { getDefaultIdentityServerUrl, doesIdentityServerHaveTerms } from '../../../utils/IdentityServerUtils'; +import {timeout} from "../../../utils/promise"; // We'll wait up to this long when checking for 3PID bindings on the IS. const REACHABILITY_TIMEOUT = 10000; // ms @@ -245,14 +246,11 @@ export default class SetIdServer extends React.Component { let threepids = []; let currentServerReachable = true; try { - threepids = await Promise.race([ + threepids = await timeout( getThreepidsWithBindStatus(MatrixClientPeg.get()), - new Promise((resolve, reject) => { - setTimeout(() => { - reject(new Error("Timeout attempting to reach identity server")); - }, REACHABILITY_TIMEOUT); - }), - ]); + Promise.reject(new Error("Timeout attempting to reach identity server")), + REACHABILITY_TIMEOUT, + ); } catch (e) { currentServerReachable = false; console.warn( diff --git a/src/utils/promise.js b/src/utils/promise.js index 8842bfa1b7..f7a2e7c3e7 100644 --- a/src/utils/promise.js +++ b/src/utils/promise.js @@ -22,6 +22,19 @@ import Promise from "bluebird"; // Returns a promise which resolves with a given value after the given number of ms export const sleep = (ms: number, value: any): Promise => new Promise((resolve => { setTimeout(resolve, ms, value); })); +// Returns a promise which resolves when the input promise resolves with its value +// or when the timeout of ms is reached with the value of given timeoutValue +export async function timeout(promise: Promise, timeoutValue: any, ms: number): Promise { + const timeoutPromise = new Promise((resolve) => { + const timeoutId = setTimeout(resolve, ms, timeoutValue); + promise.then(() => { + clearTimeout(timeoutId); + }); + }); + + return Promise.race([promise, timeoutPromise]); +} + // Returns a Deferred export function defer(): {resolve: () => {}, reject: () => {}, promise: Promise} { let resolve;