X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FUtils.ts;h=fb8aebfe0dae72f3415c3ab9f7c9d3cb08e68471;hb=f902e1c441c6751f885e39bc5aa23721a102f424;hp=b04814a7a6437dd6a369b81b5998458f652e3465;hpb=72740232578802cecbae5fcf13dc491b92417cce;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index b04814a7..fb8aebfe 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -14,7 +14,7 @@ export default class Utils { } public static async sleep(milliSeconds: number): Promise { - return new Promise((resolve) => setTimeout(resolve, milliSeconds)); + return new Promise((resolve) => setTimeout(resolve as () => void, milliSeconds)); } public static formatDurationMilliSeconds(duration: number): string { @@ -235,6 +235,24 @@ export default class Utils { return Configuration.getWorkerProcess() === WorkerProcessType.DYNAMIC_POOL; } + public static async promiseWithTimeout( + promise: Promise, + timeoutMs: number, + timeoutError: Error, + timeoutCallback: () => void = () => { /* This is intentional */ } + ): Promise { + // Create a timeout promise that rejects in timeout milliseconds + const timeoutPromise = new Promise((_, reject) => { + setTimeout(() => { + timeoutCallback(); + reject(timeoutError); + }, timeoutMs); + }); + + // Returns a race between timeout promise and the passed promise + return Promise.race([promise, timeoutPromise]); + } + /** * Generate a cryptographically secure random number in the [0,1[ range *