Quellcode durchsuchen

DRY for promise resolve in main loop or chunk event handler

Ivan Asmer vor 6 Jahren
Ursprung
Commit
def75d01a8
1 geänderte Dateien mit 9 neuen und 13 gelöschten Zeilen
  1. 9 13
      index.js

+ 9 - 13
index.js

@@ -49,23 +49,23 @@ function asynchronize({s, chunkEventName="message", endEventName="close"}){
         //buffer of promises yielding outside
         const promises      = {};
 
-        const clear = i => (delete chunks[i], delete promises[i])
+        const clear         = i => (delete chunks[i], delete promises[i])
 
 
         let   chunkCount    = 0; //autoincrement of chunks
         let   promiseCount  = 0; //autoincrement of promises
         let   end           = false; //flag
 
+        //check availability of chunk and promise. If any, resolve promise, and clear both from queue 
+        const chunkAndPromise = i  =>   (i in chunks) && 
+                                        (i in promises) && (
+                                            promises[i].resolve(chunks[i]),
+                                            clear(i))
+
         s.on(chunkEventName, data => {
             chunks[chunkCount] = data
+            chunkAndPromise(chunkCount)
 
-            //if we've gived promise for current chunk
-            if (chunkCount in promises){ 
-                //resolving it 
-                promises[chunkCount].resolve(chunks[chunkCount])
-                //and remove from both queues
-                clear(chunkCount)
-            }
             chunkCount++
         })
 
@@ -83,11 +83,7 @@ function asynchronize({s, chunkEventName="message", endEventName="close"}){
             let p;
             promises[promiseCount] = p = openPromise();
 
-            if (promiseCount in chunks){ //if chunk for this promise already exists
-                p.resolve(chunks[promiseCount]) //resolve it
-                //and clear this chunk and promise from queues
-                clear(promiseCount)
-            }
+            chunkAndPromise(promiseCount)
 
             promiseCount++;
             yield p; //yield promise outside