pool.js 1.3 KB

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