Skip to content

Instantly share code, notes, and snippets.

@antomor
Last active October 21, 2020 19:30
Show Gist options
  • Select an option

  • Save antomor/eb35bb94065c1d6ec914ef5c1a20f829 to your computer and use it in GitHub Desktop.

Select an option

Save antomor/eb35bb94065c1d6ec914ef5c1a20f829 to your computer and use it in GitHub Desktop.

Revisions

  1. antomor revised this gist Oct 21, 2020. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion retry.js
    Original file line number Diff line number Diff line change
    @@ -37,7 +37,7 @@ const resolveAfterTimes = (times) => {
    const resolveAfter5Times = resolveAfterTimes(5);

    retry({
    fn:resolveAfter,
    fn:resolveAfter5Times,
    maxRetries: 5,
    initialDelayMs: 200,
    intervalMs: 200
  2. antomor revised this gist Oct 21, 2020. No changes.
  3. antomor created this gist Oct 21, 2020.
    57 changes: 57 additions & 0 deletions retry.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    const wait = (milliSeconds) => {
    return new Promise((resolve) => setTimeout(() => resolve(), milliSeconds));
    };

    const retry = ({fn, maxRetries, initialDelayMs, intervalMs}) => {
    // first attempt after the initial delay
    let attempts = wait(initialDelayMs);
    if ( maxRetries > 0) {
    attempts = attempts.then(() => fn());
    }

    // the attempts after the first will be executed after waiting for the milliseconds specified
    for (let i = 1; i < maxRetries; i++) {
    attempts = attempts.catch(() => wait(intervalMs).then(() => fn()));
    }
    attempts = attempts.catch(() => {
    throw new Error(`Failed retrying ${maxRetries} times`);
    });
    return attempts;
    };

    const hello = () => console.log("Hello");

    // Simulate a number of attempts
    const resolveAfterTimes = (times) => {
    let index = 0;
    return () => {
    if (index >= times-1) {
    return Promise.resolve();
    }
    index++;
    return Promise.reject();
    }
    }

    // it resolves after 5 times
    const resolveAfter5Times = resolveAfterTimes(5);

    retry({
    fn:resolveAfter,
    maxRetries: 5,
    initialDelayMs: 200,
    intervalMs: 200
    }).then(() => hello()).catch((err) => console.error(err));

    // or in async/await context
    try {
    await retry({
    fn:resolveAfter,
    maxRetries: 5,
    initialDelayMs: 200,
    intervalMs: 200
    });
    hello();
    } catch(error) {
    console.error(error);
    }