Skip to content

Instantly share code, notes, and snippets.

@confused-Techie
Created October 10, 2023 01:32
Show Gist options
  • Save confused-Techie/830df033e39031566d9d6ea4577bdb09 to your computer and use it in GitHub Desktop.
Save confused-Techie/830df033e39031566d9d6ea4577bdb09 to your computer and use it in GitHub Desktop.
Retry function and wait until success
/**
* This example shows how we can can preform some check multiple times, and if it
* fails we wait a predetermined amount of time and try again. Only returning
* once there is a successful attempt.
*
* This can be useful such as preforming a startup check if you have a Database
* Also starting up at the same time, and want rather simple logic to wait on
* the database fully starting up.
*
* This example purposefully fails until ten attempts have been made, at which
* point it will succeed.
*/
const DELAY_TIME_MS = 1000;
const RETRY_AMOUNT = 10;
(async () => {
await waitRetry();
console.log("We are done waiting...");
})();
async function waitRetry() {
const delay = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const retry = async (fn, retries, delayMs) => {
let attempt = 0;
while(true) {
try {
console.log(`Running Attempt ${attempt+1}/${retries}...`);
return await fn();
} catch(err) {
console.log(`Attempt ${attempt+1}/${retries} failed. Retrying in ${delayMs}...`);
if (attempt++ < retries) {
await delay(delayMs);
} else {
console.error(err);
process.exit(1);
}
}
}
};
return retry(async () => {
await attemptToRun();
}, RETRY_AMOUNT, DELAY_TIME_MS);
}
let retryCount = 0;
async function attemptToRun() {
retryCount = retryCount + 1;
return new Promise((resolve, reject) => {
setTimeout(() => {
if (retryCount === 10) {
resolve("resolved");
} else {
reject("Failed");
}
}, 2000);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment