during.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. /**
  12. * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that
  13. * is passed a callback in the form of `function (err, truth)`. If error is
  14. * passed to `test` or `fn`, the main callback is immediately called with the
  15. * value of the error.
  16. *
  17. * @name during
  18. * @static
  19. * @memberOf module:ControlFlow
  20. * @method
  21. * @see [async.whilst]{@link module:ControlFlow.whilst}
  22. * @category Control Flow
  23. * @param {Function} test - asynchronous truth test to perform before each
  24. * execution of `fn`. Invoked with (callback).
  25. * @param {Function} fn - A function which is called each time `test` passes.
  26. * The function is passed a `callback(err)`, which must be called once it has
  27. * completed with an optional `err` argument. Invoked with (callback).
  28. * @param {Function} [callback] - A callback which is called after the test
  29. * function has failed and repeated execution of `fn` has stopped. `callback`
  30. * will be passed an error, if one occured, otherwise `null`.
  31. * @example
  32. *
  33. * var count = 0;
  34. *
  35. * async.during(
  36. * function (callback) {
  37. * return callback(null, count < 5);
  38. * },
  39. * function (callback) {
  40. * count++;
  41. * setTimeout(callback, 1000);
  42. * },
  43. * function (err) {
  44. * // 5 seconds have passed
  45. * }
  46. * );
  47. */
  48. function during(test, fn, callback) {
  49. callback = (0, _onlyOnce2.default)(callback || _noop2.default);
  50. function next(err) {
  51. if (err) return callback(err);
  52. test(check);
  53. }
  54. function check(err, truth) {
  55. if (err) return callback(err);
  56. if (!truth) return callback(null);
  57. fn(next);
  58. }
  59. test(check);
  60. }
  61. module.exports = exports['default'];