我想确保我以前的函数必须在Nodejs服务器端脚本执行以下代码之前完全执行

I want to make sure that my previous function must be executed completely before the following code in Nodejs server side scripting

本文关键字:执行 脚本 服务器端 代码 确保 函数 Nodejs      更新时间:2023-09-26

我想确保我的mongodb在mongoConnect函数中成功连接,在我开始查询之前,因为在NodeJS中是非阻塞的,它继续执行语句

我只是想知道是否有一些函数像"。then(function(){..})"在服务器端或任何其他类似的东西,我知道有回调函数用于目的,但我不知道如何使用它在这里,我的意思是在我的情况下。

这是我的代码:

io.sockets.on('connection', function (socket) {
mongoConnect();
//Some Query to the Database
socket.on('login',function(user)
{
        controller.loginUser(user);
 });
});
function mongoConnect()
  {
      var mongoose = require('mongoose');
       mongoose.connect('mongodb://xxxxxx-xxx-xxx.mongolab.com:xxx/xxxx');
  }

您可以使用猫鼬。一次等待'open'事件,然后执行回调。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function callback () {
   // Stuff here
});

参考这个网站:http://mongoosejs.com/docs/index.html