pool.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.queue = [];
  16. this.processing = [];
  17. }
  18. Pool.prototype.enqueue = function (task) {
  19. var _this = this;
  20. return new _promise["default"](function (resolve, reject) {
  21. _this.queue.push({
  22. task: task,
  23. resolve: resolve,
  24. reject: reject
  25. });
  26. _this.check();
  27. });
  28. };
  29. Pool.prototype.run = function (item) {
  30. var _this = this;
  31. this.queue = this.queue.filter(function (v) {
  32. return v !== item;
  33. });
  34. this.processing.push(item);
  35. this.runTask(item.task).then(function () {
  36. _this.processing = _this.processing.filter(function (v) {
  37. return v !== item;
  38. });
  39. item.resolve();
  40. _this.check();
  41. }, function (err) {
  42. return item.reject(err);
  43. });
  44. };
  45. Pool.prototype.check = function () {
  46. var _this = this;
  47. var processingNum = this.processing.length;
  48. var availableNum = this.limit - processingNum;
  49. this.queue.slice(0, availableNum).forEach(function (item) {
  50. _this.run(item);
  51. });
  52. };
  53. return Pool;
  54. }();
  55. exports.Pool = Pool;