为啥在设置 Mongoose 连接时在 .then() 中使用 console.log() 时不打印?

Posted

技术标签:

【中文标题】为啥在设置 Mongoose 连接时在 .then() 中使用 console.log() 时不打印?【英文标题】:Why isn't console.log() printing when used in .then() while setting up Mongoose connection?为什么在设置 Mongoose 连接时在 .then() 中使用 console.log() 时不打印? 【发布时间】:2021-10-28 08:06:29 【问题描述】:

使用以下代码,终端不会打印任何内容。我认为由于await函数返回一个promise,一旦它被解决,.then()中的代码就会执行。我知道 promise 是成功的,因为终端没有打印任何内容,这意味着 .catch() 函数没有运行。

const mongoose = require("mongoose");

main().catch((err) => console.log(err));

async function main() 
    await mongoose.connect("mongodb://localhost:27017/movieApp")
    .then(() => 
         console.log("CONNECTION OPEN");
    )

【问题讨论】:

不知道 Mongoose,但我会先查看以下链接:google.com/search?q=mongoose.connect+hangs 这不是 JS 特定的问题,而是 Mongoose 和您的数据库设置的问题。提供的代码很好。 【参考方案1】:

使用thenasync/await

const mongoose = require("mongoose");

async function main() 
    await mongoose.connect("mongodb://localhost:27017/movieApp");
    console.log("CONNECTION OPEN");


main().catch((err) => console.log(err));

async/await 是一种特殊模式,可用于简化异步调用的编码。

【讨论】:

这是否意味着我可以将 console.log 移到 main() 函数之外,因为无论如何它都会被 .catch() 捕获? 不,那不一样。在async-marked 函数中,您可以编写顺序异步调用(即await-ed)。在外面,您必须使用thencatch 仅用于例外情况。

以上是关于为啥在设置 Mongoose 连接时在 .then() 中使用 console.log() 时不打印?的主要内容,如果未能解决你的问题,请参考以下文章

为啥我在第二次运行测试时在 Mongoose 中收到错误“一旦编译后无法覆盖模型”?

如何设置 useMongoClient (Mongoose 4.11.0)?

如何设置 useMongoClient (Mongoose 4.11.0)?

使用 mongoose 插入 MongoDB 时在键中使用“@”

如何在 mongoose .save().then() 之外返回一个对象?

在任何传入的回调完成后是不是会发生 Mongoose 查询 `then` 调用?