1
0

threadPool.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. class ThreadPool {
  2. #tasks = [];
  3. #activeTask = 0;
  4. #maxTasks = 1;
  5. constructor(maxTasksInPool) {
  6. this.#maxTasks = maxTasksInPool;
  7. }
  8. #runNextTask() {
  9. if (this.#activeTask >= this.#maxTasks || this.#tasks.length === 0)
  10. return;
  11. const activeTask = (this.#tasks.shift());
  12. this.#activeTask++;
  13. let taskResult = null;
  14. try {
  15. taskResult = activeTask.fnc();
  16. }
  17. catch (err) {
  18. taskResult = Promise.reject(err);
  19. }
  20. if (!(taskResult instanceof Promise))
  21. taskResult = Promise.resolve(activeTask);
  22. taskResult
  23. .then(result => {
  24. let ok = activeTask.ok;
  25. this.#activeTask--;
  26. ok(result);
  27. })
  28. .catch(err => {
  29. let ko = activeTask.ko;
  30. this.#activeTask--;
  31. ko(err);
  32. })
  33. .finally(() => {
  34. this.#runNextTask();
  35. });
  36. };
  37. pushTask(task) {
  38. return new Promise((ok, ko) => {
  39. this.#tasks.push({ fnc: task, ok: ok, ko: ko });
  40. this.#runNextTask();
  41. });
  42. }
  43. }
  44. module.exports = ThreadPool;