retryable.js 2.5 KB

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