JSFiddle - React, Tailwind, and code Playground
by Neal
JavaScript
class Queue {
constructor(autorun = true, queue = []) {
this.running = false;
this.autorun = autorun;
this.queue = queue;
this.previousValue = undefined;
}
add(cb) {
this.queue.push((value) => {
const finished = new Promise((resolve, reject) => {
const callbackResponse = cb(value);
if (callbackResponse !== false) {
resolve(callbackResponse);
} else {
reject(callbackResponse);
}
});
finished.then(this.dequeue.bind(this), (() => {}));
});
if (this.autorun && !this.running) {
this.dequeue();
}
return this;
}
dequeue(value) {
this.running = this.queue.shift();
if (this.running) {
this.running(value);
}
return this.running;
}
get next() {
return this.dequeue;
}
}
const q = new Queue(false).add(() => {
console.log('this is a test');
return {'banana': 42};
}).add((obj) => {
console.log('test 2', obj);
return obj.banana;
}).add((number) => {
console.log('THIS IS A NUMBER', number)
});
// start the sequence
setTimeout(() => q.next(), 2000);