2016-12-05 17:25:20 -05:00
|
|
|
class Queue {
|
|
|
|
constructor() {
|
|
|
|
this.running = false;
|
|
|
|
this.queue = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
add(fn) {
|
2018-09-20 16:31:14 -04:00
|
|
|
const promise = new Promise(resolve => {
|
|
|
|
this.queue.push(async () => {
|
|
|
|
await Promise.resolve(fn());
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
|
|
|
|
if (! this.running) this.next();
|
|
|
|
});
|
|
|
|
|
|
|
|
return promise;
|
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
|
2018-09-20 16:31:14 -04:00
|
|
|
fn().then(resolve);
|
2017-02-09 21:56:36 -05:00
|
|
|
setTimeout(resolve, 10000);
|
|
|
|
}).then(() => this.next());
|
2016-12-05 17:25:20 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-20 16:31:14 -04:00
|
|
|
module.exports = {
|
|
|
|
Queue,
|
|
|
|
messageQueue: new Queue()
|
|
|
|
};
|