I’m still somewhat new to asynchronous programming and I’ve been wondering if there’s a better way to accomplish what I’m trying to do.
exports.content = function(req, res){
OPID = req.params.id;
titles.findOne({postID: OPID}, function (err, post) { //function #1
if (err) throw(err);
readComment(OPID, function(comment){ //function #2
branchFilter.getBranches(function(branches){ //function #3
res.render('content', {title: post.title, content: post.body, OPID: post.postID, comments: comment, branches: branches});
})
});
});
};
In this example I have three nested function which use callbacks to retrieve data from other modules. I need to have all this data in the res.render statement. I imagine if I continue with this approach I’m going to need even more nested functions. Is there a better way of doing this?
As JohnnyHK suggested, a good async library will help you out with this. I would also suggest Caolan’s async. You can get around pretty much any asynchronous problem with a combination of
autoandforEach, although if runtime is an issueasyncmay not be the best choice. I would rewrite your code as follows:What
autodoes is takes a dictionary of functions (with optional dependencies on other functions in the dictionary – see the async readme for more) and passes the results as a dictionary to the second argument, a “final” function.If any of the functions passes a non-null
errto its callback (the first argument), it stops calling other functions and immediately passeserrand anullresults to the “final” function.Note how I had to pass anonymous functions in the
branchesandcommentfunctions. This is becauseauto, like the other functions in thisasynclibrary, expects the first argument to its callback to be the error value and the second to be the results.