Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to convert Markdown to HTML in Node.js / Express / MongoDB app

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to convert Markdown to HTML in Node.js / Express / MongoDB app

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×