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'); };