concurrency.js 1.2 KB

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