concurrency.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.concurrency = void 0;
  4. const go_1 = require("./go");
  5. class Task {
  6. constructor(code) {
  7. this.code = code;
  8. this.promise = new Promise((resolve, reject) => {
  9. this.resolve = resolve;
  10. this.reject = reject;
  11. });
  12. }
  13. }
  14. /** Limits concurrency of async code. */
  15. const concurrency = (limit) => {
  16. let workers = 0;
  17. const queue = new Set();
  18. const work = async () => {
  19. const task = queue.values().next().value;
  20. if (task)
  21. queue.delete(task);
  22. else
  23. return;
  24. workers++;
  25. try {
  26. task.resolve(await task.code());
  27. }
  28. catch (error) {
  29. task.reject(error);
  30. }
  31. finally {
  32. workers--, queue.size && (0, go_1.go)(work);
  33. }
  34. };
  35. return async (code) => {
  36. const task = new Task(code);
  37. queue.add(task);
  38. return workers < limit && (0, go_1.go)(work), task.promise;
  39. };
  40. };
  41. exports.concurrency = concurrency;
  42. //# sourceMappingURL=concurrency.js.map