You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AsyncQueue.js 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import { getLogger } from '@jitsi/logger';
  2. import { queue } from 'async';
  3. const logger = getLogger(__filename);
  4. /**
  5. * A queue for async task execution.
  6. */
  7. export default class AsyncQueue {
  8. /**
  9. * Creates new instance.
  10. */
  11. constructor() {
  12. this._queue = queue(this._processQueueTasks.bind(this), 1);
  13. this._stopped = false;
  14. }
  15. /**
  16. * Removes any pending tasks from the queue.
  17. */
  18. clear() {
  19. this._queue.kill();
  20. }
  21. /**
  22. * Internal task processing implementation which makes things work.
  23. */
  24. _processQueueTasks(task, finishedCallback) {
  25. try {
  26. task(finishedCallback);
  27. } catch (error) {
  28. logger.error(`Task failed: ${error?.stack}`);
  29. finishedCallback(error);
  30. }
  31. }
  32. /**
  33. * Pauses the execution of the tasks on the queue.
  34. */
  35. pause() {
  36. this._queue.pause();
  37. }
  38. /**
  39. * The 'task' function will be given a callback it MUST call with either:
  40. * 1) No arguments if it was successful or
  41. * 2) An error argument if there was an error
  42. * If the task wants to process the success or failure of the task, it
  43. * should pass the {@code callback} to the push function, e.g.:
  44. * queue.push(task, (err) => {
  45. * if (err) {
  46. * // error handling
  47. * } else {
  48. * // success handling
  49. * }
  50. * });
  51. *
  52. * @param {function} task - The task to be executed. See the description above.
  53. * @param {function} [callback] - Optional callback to be called after the task has been executed.
  54. */
  55. push(task, callback) {
  56. if (this._stopped) {
  57. callback && callback(new Error('The queue has been stopped'));
  58. return;
  59. }
  60. this._queue.push(task, callback);
  61. }
  62. /**
  63. * Resumes the execution of the tasks on the queue.
  64. */
  65. resume() {
  66. this._queue.resume();
  67. }
  68. /**
  69. * Shutdowns the queue. All already queued tasks will execute, but no future tasks can be added. If a task is added
  70. * after the queue has been shutdown then the callback will be called with an error.
  71. */
  72. shutdown() {
  73. this._stopped = true;
  74. }
  75. }