作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
请看下面的代码片段。我希望仅在获得第一个结果后才执行第二个 MongoDB 查询。但正如您想象的那样,它不会按此顺序发生。
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);
});
}
});
});
那么我的选择是什么?
有没有办法以不需要任何控制流库的方式对此进行编码?如果是,有人可以告诉我怎么做吗?
如果这确实需要使用控制流库,我应该使用哪个?异步、FuturesJs,还有什么?
最佳答案
您不需要任何控制流库,因为这些库只是在后台使用回调。
尝试这样的事情:
db.collection('student_profile', function (err, collection) {
// Suppose that `firstQuery` and `secondQuery` are functions that make your
// queries and that they're already defined.
firstQuery(function firstCallback(err, firstRes) {
// Do some logic here.
// Make your second query inside the callback
secondQuery(function secondCallback(err, secondRes) {
// More logic here
});
});
});
基本上,您要做的是从第一个查询的回调中调用第二个查询。
这可能会让您觉得嵌套很深。如果这成为一个问题,您可以通过定义函数而不是内联所有函数以及将逻辑包装在模块内部来缓解它。
关于javascript - 如何在 node.js 中强制调用同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10695621/
我是一名优秀的程序员,十分优秀!