Created
November 17, 2022 16:23
-
-
Save Setitch/4f689a2529d0ced44d10f10f26670bbd to your computer and use it in GitHub Desktop.
Time Attack Mittigator - function that exeutes the job, with minimum time needed for answer, even if the job finished earlier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This function will execute the job, but return the value from it when at least `timeout` amount of milliseconds passed | |
* @param {() => Promise<T>} job | |
* @param {number} timeout | |
* @returns {Promise<T>} | |
*/ | |
export async function TimeAttackMitigator<T>(job: () => Promise<T>, timeout = 700): Promise<T> { | |
return new Promise<T>((resolve, reject) => { | |
let canResolve = false; | |
let state: boolean | undefined; | |
let value: T; | |
let error: any; | |
const tryFinish = () => { | |
if (canResolve) { | |
if (state === true) { | |
canResolve = false; | |
resolve(value); | |
} else if (state === false) { | |
canResolve = false; | |
reject(error); | |
} | |
} | |
}; | |
setTimeout(() => { | |
canResolve = true; | |
tryFinish(); | |
}, timeout); | |
job().then((arg: T) => { | |
state = true; | |
value = arg; | |
tryFinish(); | |
}).catch((err) => { | |
state = false; | |
error = err; | |
tryFinish(); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment