How to use promise to avoid callback hell?

Viewed 8778

So I have a Posts collection

{
  id: String,
  comments: [String], # id of Comments
  links: [String], #id of Links
}

Comments: { id: String, comment: String, }

Links: { id: String, link: String, }

Find a post with comments and links belong to it by id:

Posts.findOne({id: id}, function(post) {
  Comments.find({id: post.id}, function(comments) {
    Links.find({id: post.id}, function(links) {
      res.json({post: post, comments: comment, links: links})
    })
  })
})

How to use Promise(http://mongoosejs.com/docs/promises.html) to avoid callback hell?

var query = Posts.findOne({id: id});
var promise = query.exec();

promise.then(function (post) {
  var query1 = Comments.find({id: post.id});
  var promise1 = query1.exec();
  promise1.then(function(comments) {
    var query2 = Links.find({id: post.id});
    var promise2 = query2.exec();
    promise2.then(function(links) {
      res.json({post: post, comments: comment, links: links})
    })
  })
});

Seems no good......

6 Answers
Related