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