Browse Source

make sure next() is called only once

Mike L 3 years ago
parent
commit
f53c301526
2 changed files with 10 additions and 6 deletions
  1. 5 3
      dist/koishi.js
  2. 5 3
      src/koishi.ts

+ 5 - 3
dist/koishi.js

@@ -37,7 +37,8 @@ class default_1 {
         this.next = (type, id) => {
             const queue = this.messageQueues[`${type}:${id}`];
             if (queue && queue.length) {
-                queue[0]().then(() => queue.shift()).then(() => {
+                queue[0]().then(() => {
+                    queue.shift();
                     if (!queue.length)
                         delete this.messageQueues[`${type}:${id}`];
                     else
@@ -47,10 +48,11 @@ class default_1 {
         };
         this.enqueue = (type, id, resolver) => {
             var _a, _b;
-            const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = []);
+            let wasEmpty = false;
+            const queue = (_a = this.messageQueues)[_b = `${type}:${id}`] || (_a[_b] = (() => { wasEmpty = true; return []; })());
             queue.push(() => koishi_1.sleep(200).then(resolver));
             logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
-            if (queue.length === 1)
+            if (wasEmpty)
                 this.next(type, id);
         };
         this.getChat = (session) => __awaiter(this, void 0, void 0, function* () {

+ 5 - 3
src/koishi.ts

@@ -47,7 +47,8 @@ export default class {
   private next = (type: 'private' | 'group', id: string) => {
     const queue = this.messageQueues[`${type}:${id}`];
     if (queue && queue.length) {
-      queue[0]().then(() => queue.shift()).then(() => {
+      queue[0]().then(() => {
+        queue.shift();
         if (!queue.length) delete this.messageQueues[`${type}:${id}`];
         else this.next(type, id);
       });
@@ -55,10 +56,11 @@ export default class {
   };
 
   private enqueue = (type: 'private' | 'group', id: string, resolver: () => Promise<void>) => {
-    const queue = this.messageQueues[`${type}:${id}`] ||= [];
+    let wasEmpty = false;
+    const queue = this.messageQueues[`${type}:${id}`] ||= (() => { wasEmpty = true; return []; })();
     queue.push(() => sleep(200).then(resolver));
     logger.debug(`no. of message currently queued for ${type}:${id}: ${queue.length}`);
-    if (queue.length === 1) this.next(type, id);
+    if (wasEmpty) this.next(type, id);
   };
 
   private getChat = async (session: Session): Promise<IChat> => {