during.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = during;
  6. var _noop = require('lodash/noop');
  7. var _noop2 = _interopRequireDefault(_noop);
  8. var _onlyOnce = require('./internal/onlyOnce');
  9. var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
  10. var _wrapAsync = require('./internal/wrapAsync');
  11. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. /**
  14. * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
  15. * is passed a callback in the form of `function (err, truth)`. If error is
  16. * passed to `test` or `fn`, the main callback is immediately called with the
  17. * value of the error.
  18. *
  19. * @name during
  20. * @static
  21. * @memberOf module:ControlFlow
  22. * @method
  23. * @see [async.whilst]{@link module:ControlFlow.whilst}
  24. * @category Control Flow
  25. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  26. * execution of `fn`. Invoked with (callback).
  27. * @param {AsyncFunction} fn - An async function which is called each time
  28. * `test` passes. Invoked with (callback).
  29. * @param {Function} [callback] - A callback which is called after the test
  30. * function has failed and repeated execution of `fn` has stopped. `callback`
  31. * will be passed an error, if one occurred, otherwise `null`.
  32. * @example
  33. *
  34. * var count = 0;
  35. *
  36. * async.during(
  37. * function (callback) {
  38. * return callback(null, count < 5);
  39. * },
  40. * function (callback) {
  41. * count++;
  42. * setTimeout(callback, 1000);
  43. * },
  44. * function (err) {
  45. * // 5 seconds have passed
  46. * }
  47. * );
  48. */
  49. function during(test, fn, callback) {
  50. callback = (0, _onlyOnce2.default)(callback || _noop2.default);
  51. var _fn = (0, _wrapAsync2.default)(fn);
  52. var _test = (0, _wrapAsync2.default)(test);
  53. function next(err) {
  54. if (err) return callback(err);
  55. _test(check);
  56. }
  57. function check(err, truth) {
  58. if (err) return callback(err);
  59. if (!truth) return callback(null);
  60. _fn(next);
  61. }
  62. _test(check);
  63. }
  64. module.exports = exports['default'];