parallelLimit.js 652 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. module.exports = parallelLimit;
  3. /*!
  4. * ignore
  5. */
  6. async function parallelLimit(params, fn, limit) {
  7. if (limit <= 0) {
  8. throw new Error('Limit must be positive');
  9. }
  10. if (params.length === 0) {
  11. return [];
  12. }
  13. const results = [];
  14. const executing = new Set();
  15. for (let index = 0; index < params.length; index++) {
  16. const param = params[index];
  17. const p = fn(param, index);
  18. results.push(p);
  19. executing.add(p);
  20. const clean = () => executing.delete(p);
  21. p.then(clean).catch(clean);
  22. if (executing.size >= limit) {
  23. await Promise.race(executing);
  24. }
  25. }
  26. return Promise.all(results);
  27. }