whilst.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 _wrapAsync = require('./internal/wrapAsync.js');
  8. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  9. var _awaitify = require('./internal/awaitify.js');
  10. var _awaitify2 = _interopRequireDefault(_awaitify);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /**
  13. * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when
  14. * stopped, or an error occurs.
  15. *
  16. * @name whilst
  17. * @static
  18. * @memberOf module:ControlFlow
  19. * @method
  20. * @category Control Flow
  21. * @param {AsyncFunction} test - asynchronous truth test to perform before each
  22. * execution of `iteratee`. Invoked with ().
  23. * @param {AsyncFunction} iteratee - An async function which is called each time
  24. * `test` passes. Invoked with (callback).
  25. * @param {Function} [callback] - A callback which is called after the test
  26. * function has failed and repeated execution of `iteratee` has stopped. `callback`
  27. * will be passed an error and any arguments passed to the final `iteratee`'s
  28. * callback. Invoked with (err, [results]);
  29. * @returns {Promise} a promise, if no callback is passed
  30. * @example
  31. *
  32. * var count = 0;
  33. * async.whilst(
  34. * function test(cb) { cb(null, count < 5); },
  35. * function iter(callback) {
  36. * count++;
  37. * setTimeout(function() {
  38. * callback(null, count);
  39. * }, 1000);
  40. * },
  41. * function (err, n) {
  42. * // 5 seconds have passed, n = 5
  43. * }
  44. * );
  45. */
  46. function whilst(test, iteratee, callback) {
  47. callback = (0, _onlyOnce2.default)(callback);
  48. var _fn = (0, _wrapAsync2.default)(iteratee);
  49. var _test = (0, _wrapAsync2.default)(test);
  50. var results = [];
  51. function next(err, ...rest) {
  52. if (err) return callback(err);
  53. results = rest;
  54. if (err === false) return;
  55. _test(check);
  56. }
  57. function check(err, truth) {
  58. if (err) return callback(err);
  59. if (err === false) return;
  60. if (!truth) return callback(null, ...results);
  61. _fn(next);
  62. }
  63. return _test(check);
  64. }
  65. exports.default = (0, _awaitify2.default)(whilst, 3);
  66. module.exports = exports['default'];