Reputation: 156
I am just playing around with Node and Mongoose and I am curious about the following issue:
I am trying to save documents to mongo from within a loop / interval.
The following works just fine:
setInterval(function(){
var doc = new myModel({ name: 'test' });
doc.save(function (err, doc){
if (err) return console.error(err);
doc.speak();
});
}, 1);
The following does not work:
while(true){
var doc = new myModel({ name: 'test' });
doc.save(function (err, doc){
if (err) return console.error(err);
doc.speak();
});
}
What is the explanation for this behavior? The save callback is never firing in scenario 2
Additionally, can someone comment on best practices for building "long running workers"? I am interested in using node to build background workers to process queues of data. Is a while() a bad idea? setInterval()? Additionally, I plan to use the forever module to keep the process alive
Thanks!
Upvotes: 0
Views: 167
Reputation: 312149
Node.js is single threaded so while(true)
will fully occupy the single thread, never giving the doc.save
callback a chance to run.
The second part of your question is too broad though, and you should really only ask one question at a time anyway.
Upvotes: 2