doWhilst.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in
  14. * the order of operations, the arguments `test` and `iteratee` are switched.
  15. *
  16. * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.
  17. *
  18. * @name doWhilst
  19. * @static
  20. * @memberOf module:ControlFlow
  21. * @method
  22. * @see [async.whilst]{@link module:ControlFlow.whilst}
  23. * @category Control Flow
  24. * @param {AsyncFunction} iteratee - A function which is called each time `test`
  25. * passes. Invoked with (callback).
  26. * @param {AsyncFunction} test - asynchronous truth test to perform after each
  27. * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the
  28. * non-error args from the previous callback of `iteratee`.
  29. * @param {Function} [callback] - A callback which is called after the test
  30. * function has failed and repeated execution of `iteratee` has stopped.
  31. * `callback` will be passed an error and any arguments passed to the final
  32. * `iteratee`'s callback. Invoked with (err, [results]);
  33. * @returns {Promise} a promise, if no callback is passed
  34. */
  35. function doWhilst(iteratee, test, callback) {
  36. callback = (0, _onlyOnce2.default)(callback);
  37. var _fn = (0, _wrapAsync2.default)(iteratee);
  38. var _test = (0, _wrapAsync2.default)(test);
  39. var results;
  40. function next(err, ...args) {
  41. if (err) return callback(err);
  42. if (err === false) return;
  43. results = args;
  44. _test(...args, check);
  45. }
  46. function check(err, truth) {
  47. if (err) return callback(err);
  48. if (err === false) return;
  49. if (!truth) return callback(null, ...results);
  50. _fn(next);
  51. }
  52. return check(null, true);
  53. }
  54. exports.default = (0, _awaitify2.default)(doWhilst, 3);
  55. module.exports = exports['default'];