index.js 597 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. module.exports = concurrency => {
  3. if (concurrency < 1) {
  4. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  5. }
  6. const queue = [];
  7. let activeCount = 0;
  8. const next = () => {
  9. activeCount--;
  10. if (queue.length > 0) {
  11. queue.shift()();
  12. }
  13. };
  14. return fn => new Promise((resolve, reject) => {
  15. const run = () => {
  16. activeCount++;
  17. fn().then(
  18. val => {
  19. resolve(val);
  20. next();
  21. },
  22. err => {
  23. reject(err);
  24. next();
  25. }
  26. );
  27. };
  28. if (activeCount < concurrency) {
  29. run();
  30. } else {
  31. queue.push(run);
  32. }
  33. });
  34. };