Last active
April 15, 2022 12:28
-
-
Save mostafa-hz/d35ce87d90e37bd4ff4ccf2682bad4c8 to your computer and use it in GitHub Desktop.
This function execute the another function and return the result or throw the error in the least given time, one of the use case is to protect agains timing-attack
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
export async function runForAtLeast<T>(fn: (...args: any[]) => Promise<T>, ms?: number, ...args: any[]): Promise<T> { | |
const [res] = await Promise.allSettled([ | |
fn(...args), | |
new Promise(resolve => setTimeout(resolve, ms)), | |
]); | |
switch (res.status) { | |
case 'fulfilled': | |
return res.value; | |
case 'rejected': | |
throw res.reason; | |
} | |
} |
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
runForAtLeast(async (username: string, password: string): Promise<string> => { | |
// do login | |
if (username === 'mosius' && password === '1234') { | |
return 'token'; | |
} | |
throw new Error('unauthorized'); | |
return 'token'; | |
}, 1_000, 'mosius', '12345') | |
.then(console.log) | |
.catch(console.error); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cool! I didn't know
allSettled
and1_000
existed :)))