Middle+
Įgyvendinkite Queue klasės run metodą taip, kad įgyvendinimas atitiktų naudojimo pavyzdį. Run metodas turi sekuoti perduodamas asinchronines funkcijas. Kitos funkcijos eilėje gali būti iškviestos tik po to, kai iškviesite next. Jei kuri nors funkcija sukels klaidą, vėlesnės funkcijos nebus iškviečiamos. Metodai turi palaikyti grandininį kvietimą (chaining).
sobes.tech AI
Atsakymas iš AI
Ниже пример реализации класса 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();