concurrent.js 853 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. // src/utils/concurrent.ts
  2. var DEFAULT_CONCURRENCY = 1024;
  3. var createPool = ({
  4. concurrency,
  5. interval
  6. } = {}) => {
  7. concurrency ||= DEFAULT_CONCURRENCY;
  8. if (concurrency === Infinity) {
  9. return {
  10. run: async (fn) => fn()
  11. };
  12. }
  13. const pool = /* @__PURE__ */ new Set();
  14. const run = async (fn, promise, resolve) => {
  15. if (pool.size >= concurrency) {
  16. promise ||= new Promise((r) => resolve = r);
  17. setTimeout(() => run(fn, promise, resolve));
  18. return promise;
  19. }
  20. const marker = {};
  21. pool.add(marker);
  22. const result = await fn();
  23. if (interval) {
  24. setTimeout(() => pool.delete(marker), interval);
  25. } else {
  26. pool.delete(marker);
  27. }
  28. if (resolve) {
  29. resolve(result);
  30. return promise;
  31. } else {
  32. return result;
  33. }
  34. };
  35. return { run };
  36. };
  37. export {
  38. createPool
  39. };