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 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * The 'task' function will be given a callback it MUST call with either:
  34. * 1) No arguments if it was successful or
  35. * 2) An error argument if there was an error
  36. * If the task wants to process the success or failure of the task, it
  37. * should pass the {@code callback} to the push function, e.g.:
  38. * queue.push(task, (err) => {
  39. * if (err) {
  40. * // error handling
  41. * } else {
  42. * // success handling
  43. * }
  44. * });
  45. *
  46. * @param {function} task - The task to be executed. See the description above.
  47. * @param {function} [callback] - Optional callback to be called after the task has been executed.
  48. */
  49. push(task, callback) {
  50. if (this._stopped) {
  51. callback && callback(new Error('The queue has been stopped'));
  52. return;
  53. }
  54. this._queue.push(task, callback);
  55. }
  56. /**
  57. * Shutdowns the queue. All already queued tasks will execute, but no future tasks can be added. If a task is added
  58. * after the queue has been shutdown then the callback will be called with an error.
  59. */
  60. shutdown() {
  61. this._stopped = true;
  62. }
  63. }