Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. return fn => new Promise((resolve, reject) => {
  16. const run = () => {
  17. activeCount++;
  18. pTry(fn).then(
  19. val => {
  20. resolve(val);
  21. next();
  22. },
  23. err => {
  24. reject(err);
  25. next();
  26. }
  27. );
  28. };
  29. if (activeCount < concurrency) {
  30. run();
  31. } else {
  32. queue.push(run);
  33. }
  34. });
  35. };