Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. class Pool {
  2.  
  3. constructor (queues, options) {
  4. options = options || {};
  5. this._polling = options.polling || 100;
  6. this._qq = [];
  7. for (let i = 0; i < queues; i++) {
  8. this._qq.push(new Queue(i + 1));
  9. }
  10. }
  11.  
  12. addTask (weight, task) {
  13. if (typeof(weight) === "function") {
  14. task = weight;
  15. weight = 1;
  16. }
  17.  
  18. let queue = this._qq[0];
  19. if (this._qq.length > 1) {
  20. for (const q of this._qq) {
  21. if (queue.weight === 0) break;
  22. if (q.weight < queue.weight) queue = q;
  23. };
  24. };
  25. queue.add(weight, task);
  26. }
  27.  
  28. addBatch (tasks) {
  29. for (const task of tasks) {
  30. this.addTask(task);
  31. }
  32. }
  33.  
  34. wait (timeout = null) {
  35. const start = new Date();
  36.  
  37. return new Promise((resolve, reject) => {
  38. const timerId = setInterval(() => {
  39.  
  40. let q, isFinished = true;
  41. for (q of this._qq) {
  42. if (q.weight > 0) {
  43. isFinished = false;
  44. break;
  45. }
  46. }
  47.  
  48. if (isFinished) {
  49. clearInterval(timerId);
  50. resolve();
  51. return;
  52. }
  53.  
  54. if (timeout != null && (new Date() - start > timeout)) {
  55. clearInterval(timerId);
  56. for (q of this._qq) {
  57. q.close();
  58. }
  59. reject(Error(`Timeout ${timeout} ms has expired`));
  60. return;
  61. }
  62. }, this._polling);
  63. })
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement