Skip to content

Setting retry timeout on entire retry operation #98

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@
var retrier = require('retry');

function retry(fn, opts) {
var options = opts || {};

// Default `randomize` to true
if (!('randomize' in options)) {
options.randomize = true;
}

function run(resolve, reject) {
var options = opts || {};
var op;

// Default `randomize` to true
if (!('randomize' in options)) {
options.randomize = true;
}

op = retrier.operation(options);

// We allow the user to abort retrying
Expand Down Expand Up @@ -55,7 +56,18 @@ function retry(fn, opts) {
op.attempt(runAttempt);
}

return new Promise(run);
// Setting up overall timeout for a retry
const { retryTimeout } = options;
return retryTimeout
? Promise.race([
new Promise(run),
new Promise((_, reject) => {
setTimeout(() => {
reject(new Error(`Retry timed out in ${retryTimeout}ms`));
}, retryTimeout);
}),
])
: new Promise(run);
}

module.exports = retry;
16 changes: 16 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,19 @@ test('with number of retries', async t => {
t.deepEqual(retries, 2);
}
});

test('with retry timeout', async t => {
const retryTimeout = 2000;
try {
await retry(
async () => {
await sleep(3000);
},
{
retryTimeout,
}
);
} catch (err) {
t.deepEqual(err.message, `Retry timed out in ${retryTimeout}ms`);
}
});