Node.js Streams on(end) completing before asynchronous on(readable) completed Node.js Streams on(end) completing before asynchronous on(readable) completed mongoose mongoose

Node.js Streams on(end) completing before asynchronous on(readable) completed


You'll need to keep track of a counter and a boolean. Increment the counter when the "readable" event first fires and decrement the counter when you're finished saving it to the database. The boolean starts out in one state and is switched when the "end" event fires. For example:

 var processing = 0, done = false; var finished = function(){     if(processing === 0 && done){         feed.save();         // ... other stuff     } }; feedparser.on("readable", function(){     processing++;     doStuff(something, function(){         // something asynchronous                  processing--;         finished();     }); }); feedparser.on("end", function(){     done = true;     finished(); });