diff options
author | Graeme Yeates <yeatesgraeme@gmail.com> | 2016-07-11 19:56:34 -0400 |
---|---|---|
committer | Graeme Yeates <yeatesgraeme@gmail.com> | 2016-07-11 19:57:45 -0400 |
commit | b46ec26ccdd4650e6e78b7f28233aec26c43ea0e (patch) | |
tree | b2be0f11bacae5517ca16d7af5445885d9368e54 | |
parent | d4ee15d19dd4d7079e6cc65fd9ad40918d8815b7 (diff) | |
download | async-b46ec26ccdd4650e6e78b7f28233aec26c43ea0e.tar.gz |
#1226, make retry interval asynchronousasync-retry-interval
-rw-r--r-- | lib/retry.js | 44 | ||||
-rw-r--r-- | 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(); + }); + }); }); |