From 69df00609ca8b6a495eb080471e21e46a692e38f Mon Sep 17 00:00:00 2001 From: Dominic Go <18517029+dominicstop@users.noreply.github.com> Date: Fri, 17 Jun 2022 20:19:32 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=AB=20Update:=20Add=20`Helpers.promise?= =?UTF-8?q?WithTimeout`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/functions/Helpers.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/functions/Helpers.ts b/src/functions/Helpers.ts index a382349..e044865 100644 --- a/src/functions/Helpers.ts +++ b/src/functions/Helpers.ts @@ -24,6 +24,20 @@ export function timeout(ms: Number) { }); }; +/** Wraps a promise that will reject if not not resolved in milliseconds */ +export function promiseWithTimeout(ms: Number, promise: Promise){ + // Create a promise that rejects in milliseconds + const timeoutPromise = new Promise((_, reject) => { + const timeoutID = setTimeout(() => { + clearTimeout(timeoutID); + reject(`Promise timed out in ${ms} ms.`) + }, ms); + }); + + // Returns a race between our timeout and the passed in promise + return Promise.race([promise, timeoutPromise]); +}; + export function pad(num: number | string, places = 2){ return String(num).padStart(places, '0'); };