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. /* tslint:disable */
  6. class Task {
  7. constructor(code) {
  8. this.code = code;
  9. this.promise = new Promise((resolve, reject) => {
  10. this.resolve = resolve;
  11. this.reject = reject;
  12. });
  13. }
  14. }
  15. /** Limits concurrency of async code. */
  16. const concurrency = (limit) => {
  17. let workers = 0;
  18. const queue = new Set();
  19. const work = async () => {
  20. const task = queue.values().next().value;
  21. if (task)
  22. queue.delete(task);
  23. else
  24. return;
  25. workers++;
  26. try {
  27. task.resolve(await task.code());
  28. }
  29. catch (error) {
  30. task.reject(error);
  31. }
  32. finally {
  33. workers--, queue.size && (0, go_1.go)(work);
  34. }
  35. };
  36. return async (code) => {
  37. const task = new Task(code);
  38. queue.add(task);
  39. return workers < limit && (0, go_1.go)(work), task.promise;
  40. };
  41. };
  42. exports.concurrency = concurrency;