Sobes.tech
Middle+

Implement the run method of the Queue class so that the implementation matches the usage example. The run method should sequentially execute the asynchronous functions passed to it. The next function in the queue can only be called after next is called. If an error occurs in one of the functions, subsequent functions are not called. Methods should support chaining.

sobes.tech AI

Answer from AI

Below is an example implementation of a Queue class with a run method that sequentially executes asynchronous functions. Each function receives next to call the next one. If an error occurs, execution is interrupted. The methods support chaining.

class Queue {
  constructor() {
    this.tasks = [];
    this.errorOccurred = false;
  }

  add(task) {
    this.tasks.push(task);
    return this; // for chaining
  }

  run() {
    const next = (err) => {
      if (err) {
        this.errorOccurred = true;
        return;
      }
      if (this.tasks.length === 0) return;
      const task = this.tasks.shift();
      try {
        task(next);
      } catch (error) {
        this.errorOccurred = true;
      }
    };

    next();
    return this; // for chaining
  }
}

// Example usage:
// const q = new Queue();
// q.add(next => { setTimeout(() => { console.log('1'); next(); }, 1000); })
//  .add(next => { console.log('2'); next(); })
//  .run();
Implement the run method of the Queue class so that… - sobes.tech