繁体   English   中英

Mongoose.connect with async 无法正常工作请

[英]Mongoose.connect with async not working properly Please

我的代码没有以异步方式工作

module.exports = async function(URL,socket){

    let mongoose = require("mongoose");
    let db ;
        try{
            await mongoose.connect(URL,{useUnifiedTopology: true,useNewUrlParser: true},function(){
                console.log("Connected With the User DataBase");
                socket.emit("connected_user","Connected With your Database");
                    db  = mongoose.connection;
            });
            console.log("After the connected");
        }catch(e){
            console.log(e)
        }
   
    return DB;
    
}

这就是我想要 output 的方式; 它应该打印

与用户数据库连接

然后发出事件,然后打印

连接后

但它以相反的方式工作。 我究竟做错了什么?

您正在使用回调并等待两者。

如我所见,连接方法不需要回调 function,因此您可以这样做

module.exports = async function(URL,socket){

    let mongoose = require("mongoose");
    let db ;
        try{
            await mongoose.connect(URL,{useUnifiedTopology: true,useNewUrlParser: true});
            console.log("Connected With the User DataBase");
            socket.emit("connected_user","Connected With your Database");
            db  = mongoose.connection;
            console.log("After the connected");
        }catch(e){
            console.log(e)
        }

    return DB;

}

在你的代码中使用 async/await,

module.exports = async function(URL, socket) {
  let mongoose = require("mongoose");
  let db;
  try {
    await mongoose.connect(URL, {
      useUnifiedTopology: true,
      useNewUrlParser: true
    }, async function() {
      console.log("Connected With the User DataBase");
      await socket.emit("connected_user", "Connected With your Database");
      db = mongoose.connection;
    });
    console.log("After the connected");
  } catch (e) {
    console.log(e)
  }

  return DB;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM