You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.1 KiB

4 years ago
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = whilst;
  6. var _noop = require('lodash/noop');
  7. var _noop2 = _interopRequireDefault(_noop);
  8. var _slice = require('./internal/slice');
  9. var _slice2 = _interopRequireDefault(_slice);
  10. var _onlyOnce = require('./internal/onlyOnce');
  11. var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
  12. var _wrapAsync = require('./internal/wrapAsync');
  13. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  14. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  15. /**
  16. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  17. * stopped, or an error occurs.
  18. *
  19. * @name whilst
  20. * @static
  21. * @memberOf module:ControlFlow
  22. * @method
  23. * @category Control Flow
  24. * @param {Function} test - synchronous truth test to perform before each
  25. * execution of `iteratee`. Invoked with ().
  26. * @param {AsyncFunction} iteratee - An async function which is called each time
  27. * `test` passes. Invoked with (callback).
  28. * @param {Function} [callback] - A callback which is called after the test
  29. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  30. * will be passed an error and any arguments passed to the final `iteratee`'s
  31. * callback. Invoked with (err, [results]);
  32. * @returns undefined
  33. * @example
  34. *
  35. * var count = 0;
  36. * async.whilst(
  37. * function() { return count < 5; },
  38. * function(callback) {
  39. * count++;
  40. * setTimeout(function() {
  41. * callback(null, count);
  42. * }, 1000);
  43. * },
  44. * function (err, n) {
  45. * // 5 seconds have passed, n = 5
  46. * }
  47. * );
  48. */
  49. function whilst(test, iteratee, callback) {
  50. callback = (0, _onlyOnce2.default)(callback || _noop2.default);
  51. var _iteratee = (0, _wrapAsync2.default)(iteratee);
  52. if (!test()) return callback(null);
  53. var next = function (err /*, ...args*/) {
  54. if (err) return callback(err);
  55. if (test()) return _iteratee(next);
  56. var args = (0, _slice2.default)(arguments, 1);
  57. callback.apply(null, [null].concat(args));
  58. };
  59. _iteratee(next);
  60. }
  61. module.exports = exports['default'];