您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TaskQueue.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const logger = require('jitsi-meet-logger').getLogger(__filename);
  2. /**
  3. * Manages a queue of functions where the current function in progress will
  4. * automatically execute the next queued function.
  5. */
  6. export class TaskQueue {
  7. /**
  8. * Creates a new instance of {@link TaskQueue} and sets initial instance
  9. * variable values.
  10. */
  11. constructor() {
  12. this._queue = [];
  13. this._currentTask = null;
  14. this._onTaskComplete = this._onTaskComplete.bind(this);
  15. }
  16. /**
  17. * Adds a new function to the queue. It will be immediately invoked if no
  18. * other functions are queued.
  19. *
  20. * @param {Function} taskFunction - The function to be queued for execution.
  21. * @private
  22. * @returns {void}
  23. */
  24. enqueue(taskFunction) {
  25. this._queue.push(taskFunction);
  26. this._executeNext();
  27. }
  28. /**
  29. * If no queued task is currently executing, invokes the first task in the
  30. * queue if any.
  31. *
  32. * @private
  33. * @returns {void}
  34. */
  35. _executeNext() {
  36. if (this._currentTask) {
  37. logger.warn('Task queued while a task is in progress.');
  38. return;
  39. }
  40. this._currentTask = this._queue.shift() || null;
  41. if (this._currentTask) {
  42. logger.debug('Executing a task.');
  43. try {
  44. this._currentTask(this._onTaskComplete);
  45. } catch (error) {
  46. logger.error(`Task execution failed: ${error}`);
  47. this._onTaskComplete();
  48. }
  49. }
  50. }
  51. /**
  52. * Prepares to invoke the next function in the queue.
  53. *
  54. * @private
  55. * @returns {void}
  56. */
  57. _onTaskComplete() {
  58. this._currentTask = null;
  59. logger.debug('Task completed.');
  60. this._executeNext();
  61. }
  62. }