parallelLimit.js 980 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. module.exports = parallelLimit;
  3. /*!
  4. * ignore
  5. */
  6. function parallelLimit(fns, limit, callback) {
  7. let numInProgress = 0;
  8. let numFinished = 0;
  9. let error = null;
  10. if (limit <= 0) {
  11. throw new Error('Limit must be positive');
  12. }
  13. if (fns.length === 0) {
  14. return callback(null, []);
  15. }
  16. for (let i = 0; i < fns.length && i < limit; ++i) {
  17. _start();
  18. }
  19. function _start() {
  20. fns[numFinished + numInProgress](_done(numFinished + numInProgress));
  21. ++numInProgress;
  22. }
  23. const results = [];
  24. function _done(index) {
  25. return (err, res) => {
  26. --numInProgress;
  27. ++numFinished;
  28. if (error != null) {
  29. return;
  30. }
  31. if (err != null) {
  32. error = err;
  33. return callback(error);
  34. }
  35. results[index] = res;
  36. if (numFinished === fns.length) {
  37. return callback(null, results);
  38. } else if (numFinished + numInProgress < fns.length) {
  39. _start();
  40. }
  41. };
  42. }
  43. }