【问题标题】:How to ensure a function is executed before a console.log in Mongoose?如何确保在 Mongoose 的 console.log 之前执行函数?
【发布时间】:2015-10-21 20:58:02
【问题描述】:

我有一个函数findUser,我正在尝试使用sails、MongoDb 和mongoose 来实现它,如下所示:

  findUser(userId);

  function findUser(user_id){
    User.findOne({
            _id: user_id
        }).exec(function (err, userdata){
         //Some Logic
    });
  }
    console.log("XYZ");

这里User 是一个模型,我根据findUser 函数收到的user_id 对特定_id 执行findOne 操作。在node Inspector 中运行时我发现我的console.log 语句在我的 findUser 函数完成之前打印出来。我的问题是如何确保我的findUser 函数先执行,然后我的console.log is 打印在猫鼬中?

【问题讨论】:

  • 请注意,您的代码示例实际上并不包含对findUser 的调用。 (我认为它应该在函数定义和 console.log 调用之间。)您是否尝试将 console.log 调用放在 exec 回调中?
  • 编辑完成。我的问题是如果我有一个console.log 作为我的要求你如何确保你的findUser 先执行然后我的console.log?我不想把我的console.log 放在函数中。有办法吗?

标签: javascript node.js mongodb mongoose


【解决方案1】:

您需要将您的 console.log 放入您的 exec 回调中。

这是由于 Node.js 以及它异步运行的事实。它同时运行User.findOne 和console.log() 函数,并且不等待来自MongoDB 调用的数据返回。在 exec 承诺本身中,代码是同步运行的,因此将 console.log 放在 exec 函数中将解决问题。

function findUser(user_id){
  User.findOne({_id: user_id})
      .exec(function (err, userdata){
         //Some Logic
         console.log("XYZ")        
      });
};

【讨论】:

  • Hi nickbdyer 有没有其他方法可以确保先执行findOne,然后执行console.log?
  • 非常有兴趣了解为什么您不希望在.exec 中使用console.log()。除了回调和管道之外,我认为您无能为力。如果你想真正变得时髦,你可以使用一些带有再生器的 ECMA262 async/await 语法将其转换回 ES5。
猜你喜欢
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
相关资源
最近更新 更多