forever.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _onlyOnce = require('./internal/onlyOnce.js');
  6. var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
  7. var _ensureAsync = require('./ensureAsync.js');
  8. var _ensureAsync2 = _interopRequireDefault(_ensureAsync);
  9. var _wrapAsync = require('./internal/wrapAsync.js');
  10. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  11. var _awaitify = require('./internal/awaitify.js');
  12. var _awaitify2 = _interopRequireDefault(_awaitify);
  13. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  14. /**
  15. * Calls the asynchronous function `fn` with a callback parameter that allows it
  16. * to call itself again, in series, indefinitely.
  17. * If an error is passed to the callback then `errback` is called with the
  18. * error, and execution stops, otherwise it will never be called.
  19. *
  20. * @name forever
  21. * @static
  22. * @memberOf module:ControlFlow
  23. * @method
  24. * @category Control Flow
  25. * @param {AsyncFunction} fn - an async function to call repeatedly.
  26. * Invoked with (next).
  27. * @param {Function} [errback] - when `fn` passes an error to it's callback,
  28. * this function will be called, and execution stops. Invoked with (err).
  29. * @returns {Promise} a promise that rejects if an error occurs and an errback
  30. * is not passed
  31. * @example
  32. *
  33. * async.forever(
  34. * function(next) {
  35. * // next is suitable for passing to things that need a callback(err [, whatever]);
  36. * // it will result in this function being called again.
  37. * },
  38. * function(err) {
  39. * // if next is called with a value in its first parameter, it will appear
  40. * // in here as 'err', and execution will stop.
  41. * }
  42. * );
  43. */
  44. function forever(fn, errback) {
  45. var done = (0, _onlyOnce2.default)(errback);
  46. var task = (0, _wrapAsync2.default)((0, _ensureAsync2.default)(fn));
  47. function next(err) {
  48. if (err) return done(err);
  49. if (err === false) return;
  50. task(next);
  51. }
  52. return next();
  53. }
  54. exports.default = (0, _awaitify2.default)(forever, 2);
  55. module.exports = exports['default'];