Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Example
- const q = new Queue();
- q.enQueue(async () => {
- [CODE HERE]
- });
- */
- export default class Queue {
- constructor() {
- this.tasksQueue = [];
- this.deQueuedTask = null;
- this.currentTaskStatus = "INIT"; /* INIT, ADDING, WORKING, DONE */
- }
- EN_QUEUE = task => {
- this.tasksQueue.unshift(task);
- };
- DE_QUEUE = () => {
- this.deQueuedTask = this.tasksQueue.pop();
- };
- UPDATE_CURRENT_TASK_STATUS = status => {
- this.currentTaskStatus = status;
- };
- enQueue = async task => {
- this.EN_QUEUE(task);
- if (this.currentTaskStatus === "INIT") {
- this.UPDATE_CURRENT_TASK_STATUS("WORKING");
- while (this.tasksQueue.length) {
- this.DE_QUEUE();
- await this.runTask(this.deQueuedTask);
- if (!this.tasksQueue.length) {
- this.UPDATE_CURRENT_TASK_STATUS("INIT");
- break;
- }
- }
- }
- };
- runTask = async deQueuedTask => {
- try {
- await deQueuedTask();
- } catch (error) {
- console.log(error);
- }
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement