diff --git a/lib/index.js b/lib/index.js index d8f0c8a..1ecaf25 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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 @@ -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; diff --git a/test/index.js b/test/index.js index 81ec16b..3f7a26e 100644 --- a/test/index.js +++ b/test/index.js @@ -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`); + } +});