pool.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");
  3. var _Object$defineProperty = require("@babel/runtime-corejs2/core-js/object/define-property");
  4. _Object$defineProperty(exports, "__esModule", {
  5. value: true
  6. });
  7. exports.Pool = void 0;
  8. var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));
  9. var Pool =
  10. /** @class */
  11. function () {
  12. function Pool(runTask, limit) {
  13. this.runTask = runTask;
  14. this.limit = limit;
  15. this.aborted = false;
  16. this.queue = [];
  17. this.processing = [];
  18. }
  19. Pool.prototype.enqueue = function (task) {
  20. var _this = this;
  21. return new _promise["default"](function (resolve, reject) {
  22. _this.queue.push({
  23. task: task,
  24. resolve: resolve,
  25. reject: reject
  26. });
  27. _this.check();
  28. });
  29. };
  30. Pool.prototype.run = function (item) {
  31. var _this = this;
  32. this.queue = this.queue.filter(function (v) {
  33. return v !== item;
  34. });
  35. this.processing.push(item);
  36. this.runTask(item.task).then(function () {
  37. _this.processing = _this.processing.filter(function (v) {
  38. return v !== item;
  39. });
  40. item.resolve();
  41. _this.check();
  42. }, function (err) {
  43. return item.reject(err);
  44. });
  45. };
  46. Pool.prototype.check = function () {
  47. var _this = this;
  48. if (this.aborted) return;
  49. var processingNum = this.processing.length;
  50. var availableNum = this.limit - processingNum;
  51. this.queue.slice(0, availableNum).forEach(function (item) {
  52. _this.run(item);
  53. });
  54. };
  55. Pool.prototype.abort = function () {
  56. this.queue = [];
  57. this.aborted = true;
  58. };
  59. return Pool;
  60. }();
  61. exports.Pool = Pool;