選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AsyncQueue.js 1.7KB

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