Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. /* Example
  2.  
  3. const q = new Queue();
  4.  
  5. q.enQueue(async () => {
  6. [CODE HERE]
  7. });
  8. */
  9.  
  10. export default class Queue {
  11. constructor() {
  12. this.tasksQueue = [];
  13. this.deQueuedTask = null;
  14. this.currentTaskStatus = "INIT"; /* INIT, ADDING, WORKING, DONE */
  15. }
  16.  
  17. EN_QUEUE = task => {
  18. this.tasksQueue.unshift(task);
  19. };
  20.  
  21. DE_QUEUE = () => {
  22. this.deQueuedTask = this.tasksQueue.pop();
  23. };
  24.  
  25. UPDATE_CURRENT_TASK_STATUS = status => {
  26. this.currentTaskStatus = status;
  27. };
  28.  
  29. enQueue = async task => {
  30. this.EN_QUEUE(task);
  31.  
  32. if (this.currentTaskStatus === "INIT") {
  33. this.UPDATE_CURRENT_TASK_STATUS("WORKING");
  34.  
  35. while (this.tasksQueue.length) {
  36. this.DE_QUEUE();
  37. await this.runTask(this.deQueuedTask);
  38.  
  39. if (!this.tasksQueue.length) {
  40. this.UPDATE_CURRENT_TASK_STATUS("INIT");
  41. break;
  42. }
  43. }
  44. }
  45. };
  46.  
  47. runTask = async deQueuedTask => {
  48. try {
  49. await deQueuedTask();
  50. } catch (error) {
  51. console.log(error);
  52. }
  53. };
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement