Sobes.tech
Middle+

Implemente o método run da classe Queue de forma que a implementação corresponda ao exemplo de uso. O método run deve executar sequencialmente as funções assíncronas passadas a ele. A próxima função na fila só pode ser chamada após a chamada de next. Se ocorrer um erro em alguma das funções, as funções seguintes não são chamadas. Os métodos devem suportar encadeamento (chaining).

sobes.tech IA

Resposta da IA

Ниже пример реализации класса Queue с методом run, который последовательно выполняет асинхронные функции. Каждая функция получает next для вызова следующей. Если возникает ошибка, выполнение прерывается. Методы поддерживают цепочку вызовов.

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

  add(task) {
    this.tasks.push(task);
    return this; // для 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; // для chaining
  }
}

// Пример использования:
// const q = new Queue();
// q.add(next => { setTimeout(() => { console.log('1'); next(); }, 1000); })
//  .add(next => { console.log('2'); next(); })
//  .run();