aboutsummaryrefslogtreecommitdiff
path: root/src/queue.js
diff options
context:
space:
mode:
authorSin-MacBook <[email protected]>2020-08-10 23:44:20 +0200
committerSin-MacBook <[email protected]>2020-08-10 23:44:20 +0200
commit2a53887abba882bf7b63aeda8dfa55fdb3ab8792 (patch)
treead7a95eb41faa6ff13c3142285cdc0eb3ca92183 /src/queue.js
downloadmodmail-2a53887abba882bf7b63aeda8dfa55fdb3ab8792.tar.xz
modmail-2a53887abba882bf7b63aeda8dfa55fdb3ab8792.zip
clean this up when home
Diffstat (limited to 'src/queue.js')
-rw-r--r--src/queue.js40
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()
+};