Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PR suggestion: withRetry wrapper #81

Open
LiranBri opened this issue Sep 17, 2021 · 1 comment
Open

PR suggestion: withRetry wrapper #81

LiranBri opened this issue Sep 17, 2021 · 1 comment

Comments

@LiranBri
Copy link

LiranBri commented Sep 17, 2021

Hi, I wrote an higher-level function util withRetry which makes the usage of the library very easy and also supports promises.

this is what I wrote:

const retry = require('retry');

function withRetry(callback) {
  return (...args) => {
    const operation = retry.operation({ retries: 5 });

    return new Promise((resolve, reject) => {
      operation.attempt(async function (currentAttempt) {
        try {
          const result = await callback(...args);
          resolve(result);
        } catch (err) {
          console.log(`attempt #${currentAttempt} failed. error: ${err.message}`);
          if (operation.retry(err)) {
            return;
          }
          reject(err);
        }
      });
    });
  };
}
module.exports = withRetry;

now any function could be enhanced with retry logic using a single line. e.g:

async functuin myFunc(a, b) {
   // .. bla bla async logic .. 
   return a + b
} 
module.exports = withRetry(myFunc);

if it feels useful, I can make the code more generic, and contribute as PR

@ghost
Copy link

ghost commented Apr 25, 2022

isn't that already mostly done with wrap function, although different signature?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant