whilst.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 _rest = require('./internal/rest');
  9. var _rest2 = _interopRequireDefault(_rest);
  10. var _onlyOnce = require('./internal/onlyOnce');
  11. var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. /**
  14. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  15. * stopped, or an error occurs.
  16. *
  17. * @name whilst
  18. * @static
  19. * @memberOf module:ControlFlow
  20. * @method
  21. * @category Control Flow
  22. * @param {Function} test - synchronous truth test to perform before each
  23. * execution of `iteratee`. Invoked with ().
  24. * @param {Function} iteratee - A function which is called each time `test` passes.
  25. * The function is passed a `callback(err)`, which must be called once it has
  26. * completed with an optional `err` argument. Invoked with (callback).
  27. * @param {Function} [callback] - A callback which is called after the test
  28. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  29. * will be passed an error and any arguments passed to the final `iteratee`'s
  30. * callback. Invoked with (err, [results]);
  31. * @returns undefined
  32. * @example
  33. *
  34. * var count = 0;
  35. * async.whilst(
  36. * function() { return count < 5; },
  37. * function(callback) {
  38. * count++;
  39. * setTimeout(function() {
  40. * callback(null, count);
  41. * }, 1000);
  42. * },
  43. * function (err, n) {
  44. * // 5 seconds have passed, n = 5
  45. * }
  46. * );
  47. */
  48. function whilst(test, iteratee, callback) {
  49. callback = (0, _onlyOnce2.default)(callback || _noop2.default);
  50. if (!test()) return callback(null);
  51. var next = (0, _rest2.default)(function (err, args) {
  52. if (err) return callback(err);
  53. if (test()) return iteratee(next);
  54. callback.apply(null, [null].concat(args));
  55. });
  56. iteratee(next);
  57. }
  58. module.exports = exports['default'];