Skip to content

Instantly share code, notes, and snippets.

@varokas
Forked from briancavalier/simple-promise-retry.js
Created August 7, 2016 13:51
Show Gist options
  • Select an option

  • Save varokas/e61ea4b15fad9002e28a29c13ff33a96 to your computer and use it in GitHub Desktop.

Select an option

Save varokas/e61ea4b15fad9002e28a29c13ff33a96 to your computer and use it in GitHub Desktop.

Revisions

  1. @briancavalier briancavalier revised this gist Feb 24, 2011. 3 changed files with 33 additions and 0 deletions.
    File renamed without changes.
    17 changes: 17 additions & 0 deletions with-incremental-backoff.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    function keepTrying(otherArgs, retryInterval, promise) {
    promise = promise||new Promise();

    // try doing the important thing

    if(success) {
    promise.resolve(result);
    } else {
    setTimeout(function() {
    // Try again with incremental backoff, 2 can be
    // anything you want. You could even pass it in.
    // Cap max retry interval, which probably makes sense
    // in most cases.
    keepTrying(otherArgs, Math.min(maxRetryInterval, retryInterval * 2), promise);
    }, retryInterval);
    }
    }
    16 changes: 16 additions & 0 deletions with-max-retries.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    function tryAtMost(otherArgs, maxRetries, promise) {
    promise = promise||new Promise();

    // try doing the important thing

    if(success) {
    promise.resolve(result);
    } else if (maxRetries > 0) {
    // Try again if we haven't reached maxRetries yet
    setTimeout(function() {
    tryAtMost(otherArgs, maxRetries - 1, promise);
    }, retryInterval);
    } else {
    promise.reject(error);
    }
    }
  2. @briancavalier briancavalier created this gist Feb 24, 2011.
    13 changes: 13 additions & 0 deletions promise-retry-pattern.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    function keepTrying(otherArgs, promise) {
    promise = promise||new Promise();

    // try doing the important thing

    if(success) {
    promise.resolve(result);
    } else {
    setTimeout(function() {
    keepTrying(otherArgs, promise);
    }, retryInterval);
    }
    }