You can do it using promises like this:
Posts.findOne({id: id}).exec().then(function(post) {
let p1 = Comments.find({id: post.id}).exec();
let p2 = Links.find({id: post.id}).exec();
return Promise.all([p1, p2]).then(function(results) {
res.json({post: post, comments: results[0], links: results[1]});
});
}).catch(function(err) {
// error here
});
This sets up two operations Comments.find().exec()
and Links.find().exec()
that both depend upon the post
variable, but are independent of each other so they can run in parallel. Then, it uses Promise.all()
to know when both are done and then the JSON can be output.
Here's the step by step description:
- Run
Posts.findOne().exec()
.
- When it's done, start both
Comments.find().exec()
and Links.find().exec()
in parallel.
- Use
Promise.all()
to know when both of those are done.
- When both of those are done, then output the JSON.
This could be done with less nesting, but because you're using prior results in subsequent requests or in the final JSON, it's easier to nest it a bit.
You can see various options for sharing prior results while chaining promise requests in this other answer How to chain and share prior results.
FYI, where this promise implementation really shines compare to what you show in your question is for error handling. Your non-promise code shows no error handling, but the promise version will propagate all errors up to the .catch()
handler for you.