diff options
Diffstat (limited to 'src/queue.js')
| -rw-r--r-- | src/queue.js | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/queue.js b/src/queue.js new file mode 100644 index 0000000..589425e --- /dev/null +++ b/src/queue.js @@ -0,0 +1,40 @@ +class Queue { + constructor() { + this.running = false; + this.queue = []; + } + + add(fn) { + const promise = new Promise(resolve => { + this.queue.push(async () => { + await Promise.resolve(fn()); + resolve(); + }); + + if (! this.running) this.next(); + }); + + return promise; + } + + next() { + this.running = true; + + if (this.queue.length === 0) { + this.running = false; + return; + } + + const fn = this.queue.shift(); + new Promise(resolve => { + // Either fn() completes or the timeout of 10sec is reached + fn().then(resolve); + setTimeout(resolve, 10000); + }).then(() => this.next()); + } +} + +module.exports = { + Queue, + messageQueue: new Queue() +}; |