ramirez/src/queue.js

30 lines
554 B
JavaScript
Raw Normal View History

2016-12-05 17:25:20 -05:00
class Queue {
constructor() {
this.running = false;
this.queue = [];
}
add(fn) {
this.queue.push(fn);
2017-02-09 21:56:36 -05:00
if (! this.running) this.next();
2016-12-05 17:25:20 -05:00
}
next() {
this.running = true;
if (this.queue.length === 0) {
this.running = false;
return;
}
const fn = this.queue.shift();
2017-02-09 21:56:36 -05:00
new Promise(resolve => {
// Either fn() completes or the timeout of 10sec is reached
Promise.resolve(fn()).then(resolve);
setTimeout(resolve, 10000);
}).then(() => this.next());
2016-12-05 17:25:20 -05:00
}
}
module.exports = Queue;