Please take a look at the code snippet below. I want the 2nd MongoDB query to be executed only after I have the results from the first one. But as you can imagine, it doesn’t happen in that order.
db.collection('student_profile', function (err, stuColl) {
//This if-else can be refactored in to a seperate function
if (req.params.stuId == req.header('x-stuId')) {
var stuInQuestion = student;
} else {
var stuInQuestionId = new ObjectID.createFromHexString(req.params.stuId);
stuColl.findOne({
'_id': stuInQuestionId
}, function (err, stuInQuestionObj) {
if (!stuInQuestionObj) {
process.nextTick(function () {
callback(null);
});
} else {
var stuInQuestion = stuInQuestionObj;
}
});
}
stuColl.find({
'_id': {
$in: stuInQuestion['courses']
}
}).limit(25).sort({
'_id': -1
}).toArray(function (error, courses) {
if (error) {
process.nextTick(function () {
callback(null);
});
} else {
process.nextTick(function () {
callback(courses);
});
}
});
});
So what are my choices here?
-
Is there a way to code this in a way that doesnt require any control flow libraries? If yes, can someone show me how?
-
If this does require use of a control flow library, which one should I use? asynch, FuturesJs, anything else?
I would create a
findStudentfunction and have both cases call it: