pool.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var Pool = /** @class */ (function () {
  2. function Pool(runTask, limit) {
  3. this.runTask = runTask;
  4. this.limit = limit;
  5. this.aborted = false;
  6. this.queue = [];
  7. this.processing = [];
  8. }
  9. Pool.prototype.enqueue = function (task) {
  10. var _this = this;
  11. return new Promise(function (resolve, reject) {
  12. _this.queue.push({
  13. task: task,
  14. resolve: resolve,
  15. reject: reject
  16. });
  17. _this.check();
  18. });
  19. };
  20. Pool.prototype.run = function (item) {
  21. var _this = this;
  22. this.queue = this.queue.filter(function (v) { return v !== item; });
  23. this.processing.push(item);
  24. this.runTask(item.task).then(function () {
  25. _this.processing = _this.processing.filter(function (v) { return v !== item; });
  26. item.resolve();
  27. _this.check();
  28. }, function (err) { return item.reject(err); });
  29. };
  30. Pool.prototype.check = function () {
  31. var _this = this;
  32. if (this.aborted)
  33. return;
  34. var processingNum = this.processing.length;
  35. var availableNum = this.limit - processingNum;
  36. this.queue.slice(0, availableNum).forEach(function (item) {
  37. _this.run(item);
  38. });
  39. };
  40. Pool.prototype.abort = function () {
  41. this.queue = [];
  42. this.aborted = true;
  43. };
  44. return Pool;
  45. }());
  46. export { Pool };
  47. //# sourceMappingURL=pool.js.map