gpt4 book ai didi

javascript - 如何在 node.js 中强制调用同步

转载 作者:可可西里 更新时间:2023-11-01 10:01:25 25 4
gpt4 key购买 nike

请看下面的代码片段。我希望仅在获得第一个结果后才执行第二个 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);
});
}
});
});

那么我的选择是什么?

  1. 有没有办法以不需要任何控制流库的方式对此进行编码?如果是,有人可以告诉我怎么做吗?

  2. 如果这确实需要使用控制流库,我应该使用哪个?异步、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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com