From b46ec26ccdd4650e6e78b7f28233aec26c43ea0e Mon Sep 17 00:00:00 2001 From: Graeme Yeates Date: Mon, 11 Jul 2016 19:56:34 -0400 Subject: #1226, make retry interval asynchronous --- lib/retry.js | 44 ++++++++++---------------------------------- mocha_test/retry.js | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 34 deletions(-) diff --git a/lib/retry.js b/lib/retry.js index 5c22af3..bf0dcf1 100644 --- a/lib/retry.js +++ b/lib/retry.js @@ -1,4 +1,3 @@ -import series from './series'; import noop from 'lodash/noop'; import constant from 'lodash/constant'; @@ -104,43 +103,20 @@ export default function retry(opts, task, callback) { callback = callback || noop; } - if (typeof task !== 'function') { throw new Error("Invalid arguments for async.retry"); } - var attempts = []; - for (var i = 1; i < options.times + 1; i++) { - var isFinalAttempt = (i == options.times); - attempts.push(retryAttempt(isFinalAttempt)); - var interval = options.intervalFunc(i); - if (!isFinalAttempt && interval > 0) { - attempts.push(retryInterval(interval)); - } + var attempt = 1; + function retryAttempt() { + task(function(err, result) { + if (err && attempt++ < options.times) { + setTimeout(retryAttempt, options.intervalFunc(attempt)); + } else { + callback(err, result); + } + }); } - series(attempts, function(done, data) { - data = data[data.length - 1]; - callback(data.err, data.result); - }); - - - function retryAttempt(isFinalAttempt) { - return function(seriesCallback) { - task(function(err, result) { - seriesCallback(!err || isFinalAttempt, { - err: err, - result: result - }); - }); - }; - } - - function retryInterval(interval) { - return function(seriesCallback) { - setTimeout(function() { - seriesCallback(null); - }, interval); - }; - } + retryAttempt(); } diff --git a/mocha_test/retry.js b/mocha_test/retry.js index 43a8f6f..cc24a29 100644 --- a/mocha_test/retry.js +++ b/mocha_test/retry.js @@ -120,4 +120,20 @@ describe("retry", function () { done(); }, 50); }); + + it('retry does not precompute the intervals (#1226)',function(done) { + var callTimes = []; + function intervalFunc() { + callTimes.push(new Date().getTime()); + return 100; + }; + function fn(callback) { + callback({}); // respond with indexed values + } + async.retry({ times: 4, interval: intervalFunc}, fn, function(){ + expect(callTimes[1] - callTimes[0]).to.be.above(99); + expect(callTimes[2] - callTimes[1]).to.be.above(99); + done(); + }); + }); }); -- cgit v1.2.1