Skip to content

Instantly share code, notes, and snippets.

@BitPatty
Created November 4, 2020 15:39
Show Gist options
  • Save BitPatty/7897411036b13d5d52b0d718a9c7430f to your computer and use it in GitHub Desktop.
Save BitPatty/7897411036b13d5d52b0d718a9c7430f to your computer and use it in GitHub Desktop.
/**
* Runs the specified task until the specfied
* condition is met
*
* @param task The task to run
* @param breakCondition The breaking condition
* @param timeout The timeout between attempts in miliseconds
* @param options Additional options to tweak the timeout and
* max retry count
*/
private async runUntil<T>(
task: () => Promise<T>,
breakCondition: (data: T) => boolean,
options: {
timeout: number;
maxRetries: number;
} = {
timeout: 10000,
maxRetries: 10,
},
): Promise<T> {
const intFunc = (retryCount: number): Promise<T> =>
new Promise((resolve, reject) => {
setTimeout(async () => {
if (retryCount > options.maxRetries) {
reject('Max retry count reached');
}
try {
const res = await task();
if (breakCondition(res)) {
resolve(res);
return;
}
const d = await intFunc(retryCount + 1);
resolve(d);
} catch (err) {
reject(err);
}
}, options.timeout);
});
return intFunc(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment