retryable.js
 1  'use strict';
 2  
 3  Object.defineProperty(exports, "__esModule", {
 4      value: true
 5  });
 6  exports.default = retryable;
 7  
 8  var _retry = require('./retry');
 9  
10  var _retry2 = _interopRequireDefault(_retry);
11  
12  var _initialParams = require('./internal/initialParams');
13  
14  var _initialParams2 = _interopRequireDefault(_initialParams);
15  
16  var _wrapAsync = require('./internal/wrapAsync');
17  
18  var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
19  
20  var _promiseCallback = require('./internal/promiseCallback');
21  
22  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
23  
24  /**
25   * A close relative of [`retry`]{@link module:ControlFlow.retry}.  This method
26   * wraps a task and makes it retryable, rather than immediately calling it
27   * with retries.
28   *
29   * @name retryable
30   * @static
31   * @memberOf module:ControlFlow
32   * @method
33   * @see [async.retry]{@link module:ControlFlow.retry}
34   * @category Control Flow
35   * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional
36   * options, exactly the same as from `retry`, except for a `opts.arity` that
37   * is the arity of the `task` function, defaulting to `task.length`
38   * @param {AsyncFunction} task - the asynchronous function to wrap.
39   * This function will be passed any arguments passed to the returned wrapper.
40   * Invoked with (...args, callback).
41   * @returns {AsyncFunction} The wrapped function, which when invoked, will
42   * retry on an error, based on the parameters specified in `opts`.
43   * This function will accept the same parameters as `task`.
44   * @example
45   *
46   * async.auto({
47   *     dep1: async.retryable(3, getFromFlakyService),
48   *     process: ["dep1", async.retryable(3, function (results, cb) {
49   *         maybeProcessData(results.dep1, cb);
50   *     })]
51   * }, callback);
52   */
53  function retryable(opts, task) {
54      if (!task) {
55          task = opts;
56          opts = null;
57      }
58      let arity = opts && opts.arity || task.length;
59      if ((0, _wrapAsync.isAsync)(task)) {
60          arity += 1;
61      }
62      var _task = (0, _wrapAsync2.default)(task);
63      return (0, _initialParams2.default)((args, callback) => {
64          if (args.length < arity - 1 || callback == null) {
65              args.push(callback);
66              callback = (0, _promiseCallback.promiseCallback)();
67          }
68          function taskFn(cb) {
69              _task(...args, cb);
70          }
71  
72          if (opts) (0, _retry2.default)(opts, taskFn, callback);else (0, _retry2.default)(taskFn, callback);
73  
74          return callback[_promiseCallback.PROMISE_SYMBOL];
75      });
76  }
77  module.exports = exports['default'];