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

标签 javascript node.js mongodb express

请看一下下面的代码片段。我希望只有在获得第一个查询的结果后才执行第二个 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/

相关文章:

node.js - 通过 API 将 Twilio Voice Response 设置为 URL 而不是 TwiML 应用程序

javascript - xcode 使用错误的 node.js 版本

javascript - 如何在 mongodb 中将 $push 、 $set 和 $inc 放在一起?

mongodb - 教义2 MongoDB获取对象的子记录

node.js - Expresso 测试在导航到静态文件时返回 'Error: Response not completed'

javascript - 无法在简单的node.js应用程序中找到模块mongodb

javascript - firebase 电子邮件验证网络

javascript - 连接特定列中的数据

node.js - Mongoose 虚拟填充和聚合

javascript - 我想打印 "2019 to 2020"当前它显示 2019-04-01 到 2020-03-31