index.js 908 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. const pTry = require('p-try');
  3. module.exports = concurrency => {
  4. if (concurrency < 1) {
  5. throw new TypeError('Expected `concurrency` to be a number from 1 and up');
  6. }
  7. const queue = [];
  8. let activeCount = 0;
  9. const next = () => {
  10. activeCount--;
  11. if (queue.length > 0) {
  12. queue.shift()();
  13. }
  14. };
  15. const run = (fn, resolve, ...args) => {
  16. activeCount++;
  17. const result = pTry(fn, ...args);
  18. resolve(result);
  19. result.then(next, next);
  20. };
  21. const enqueue = (fn, resolve, ...args) => {
  22. if (activeCount < concurrency) {
  23. run(fn, resolve, ...args);
  24. } else {
  25. queue.push(run.bind(null, fn, resolve, ...args));
  26. }
  27. };
  28. const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
  29. Object.defineProperties(generator, {
  30. activeCount: {
  31. get: () => activeCount
  32. },
  33. pendingCount: {
  34. get: () => queue.length
  35. }
  36. });
  37. return generator;
  38. };