(opts, task, callback)
| 87 | * |
| 88 | */ |
| 89 | export default function retry(opts, task, callback) { |
| 90 | var DEFAULT_TIMES = 5; |
| 91 | var DEFAULT_INTERVAL = 0; |
| 92 | |
| 93 | var options = { |
| 94 | times: DEFAULT_TIMES, |
| 95 | intervalFunc: constant(DEFAULT_INTERVAL) |
| 96 | }; |
| 97 | |
| 98 | function parseTimes(acc, t) { |
| 99 | if (typeof t === 'object') { |
| 100 | acc.times = +t.times || DEFAULT_TIMES; |
| 101 | |
| 102 | acc.intervalFunc = typeof t.interval === 'function' ? |
| 103 | t.interval : |
| 104 | constant(+t.interval || DEFAULT_INTERVAL); |
| 105 | |
| 106 | acc.errorFilter = t.errorFilter; |
| 107 | } else if (typeof t === 'number' || typeof t === 'string') { |
| 108 | acc.times = +t || DEFAULT_TIMES; |
| 109 | } else { |
| 110 | throw new Error("Invalid arguments for async.retry"); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | if (arguments.length < 3 && typeof opts === 'function') { |
| 115 | callback = task || noop; |
| 116 | task = opts; |
| 117 | } else { |
| 118 | parseTimes(options, opts); |
| 119 | callback = callback || noop; |
| 120 | } |
| 121 | |
| 122 | if (typeof task !== 'function') { |
| 123 | throw new Error("Invalid arguments for async.retry"); |
| 124 | } |
| 125 | |
| 126 | var _task = wrapAsync(task); |
| 127 | |
| 128 | var attempt = 1; |
| 129 | function retryAttempt() { |
| 130 | _task(function(err) { |
| 131 | if (err && attempt++ < options.times && |
| 132 | (typeof options.errorFilter != 'function' || |
| 133 | options.errorFilter(err))) { |
| 134 | setTimeout(retryAttempt, options.intervalFunc(attempt)); |
| 135 | } else { |
| 136 | callback.apply(null, arguments); |
| 137 | } |
| 138 | }); |
| 139 | } |
| 140 | |
| 141 | retryAttempt(); |
| 142 | } |
no test coverage detected
searching dependent graphs…