【发布时间】:2021-01-22 18:20:34
【问题描述】:
我想知道我在这里做错了什么。我无法连接到服务器并给我一条消息,说承诺被拒绝并且没有被 catch() 处理。我在某处缺少异步功能吗?提前致谢。
const mongoose = require("mongoose");
const Dishes = require("./models/dishes");
const url = "mongodb://localhost:27017/conFusion";
const connect = mongoose.connect(url);
mongoose.set("useUnifiedTopology", true);
mongoose.set("useNewUrlParser", true);
connect.then(db => {
console.log("Connected correctly to server");
var newDish = Dishes({
name: "Uthappizza",
description: "test"
});
newDish
.save()
.then(dish => {
console.log(dish);
return Dishes.find({});
})
.then(dishes => {
console.log(dishes);
return Dishes.remove({});
})
.then(() => {
return mongoose.connection.close();
})
.catch(err => {
console.log(err);
});
});
【问题讨论】:
-
对于来自
mongoose.connect本身的承诺(您的connect常量),您没有拒绝处理程序。你只使用then,而不是catch,并且你没有将第二个参数提供给then。 -
你拥有的
catch()只捕获从newDish开始的 Promise 链中发生的拒绝,但你甚至都达不到,因为connect已经抛出。
标签: node.js asynchronous promise unhandled