项目原始demo,不改动
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
 
 
 
 

43 line
633 B

  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. };