Skip to content

Instantly share code, notes, and snippets.

@mostafa-hz
Last active April 15, 2022 12:28
Show Gist options
  • Save mostafa-hz/d35ce87d90e37bd4ff4ccf2682bad4c8 to your computer and use it in GitHub Desktop.
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
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;
}
}
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);
@manishoo
Copy link

Cool! I didn't know allSettled and 1_000 existed :)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment