asyncEachOfLimit.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = asyncEachOfLimit;
  6. var _breakLoop = require('./breakLoop.js');
  7. var _breakLoop2 = _interopRequireDefault(_breakLoop);
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. // for async generators
  10. function asyncEachOfLimit(generator, limit, iteratee, callback) {
  11. let done = false;
  12. let canceled = false;
  13. let awaiting = false;
  14. let running = 0;
  15. let idx = 0;
  16. function replenish() {
  17. //console.log('replenish')
  18. if (running >= limit || awaiting || done) return;
  19. //console.log('replenish awaiting')
  20. awaiting = true;
  21. generator.next().then(({ value, done: iterDone }) => {
  22. //console.log('got value', value)
  23. if (canceled || done) return;
  24. awaiting = false;
  25. if (iterDone) {
  26. done = true;
  27. if (running <= 0) {
  28. //console.log('done nextCb')
  29. callback(null);
  30. }
  31. return;
  32. }
  33. running++;
  34. iteratee(value, idx, iterateeCallback);
  35. idx++;
  36. replenish();
  37. }).catch(handleError);
  38. }
  39. function iterateeCallback(err, result) {
  40. //console.log('iterateeCallback')
  41. running -= 1;
  42. if (canceled) return;
  43. if (err) return handleError(err);
  44. if (err === false) {
  45. done = true;
  46. canceled = true;
  47. return;
  48. }
  49. if (result === _breakLoop2.default || done && running <= 0) {
  50. done = true;
  51. //console.log('done iterCb')
  52. return callback(null);
  53. }
  54. replenish();
  55. }
  56. function handleError(err) {
  57. if (canceled) return;
  58. awaiting = false;
  59. done = true;
  60. callback(err);
  61. }
  62. replenish();
  63. }
  64. module.exports = exports['default'];