How to convert Markdown to HTML in Node.js / Express / MongoDB app
Problem
I have this snippet of code which works just fine; however, is this good design? I'm concerned about the res.send() executing before the for loop has had a chance to finish.
app.get('/api/ideas', function(req, res) {
var query = Idea.find({ status: 'published' }, 'title slug status body pub_date').sort({pub_date: -1});
query.exec(function(err, ideas){
for(i in ideas) {
ideas[i].body = markdown.toHTML(ideas[i].body);
}
res.send(ideas);
});
});
Problem courtesy of: doremi
Solution
I'm not sure what the toHTML method is but you need to see if it's a synchronous or asynchronous call. If it's synchronous then your design is perfectly fine, and res.send will only execute after the for loop is done. If it's async, then this won't work and send will execute before the for loop is complete.
Solution courtesy of: BFree
Discussion
View additional discussion.