【问题标题】:Unhandled promise rejection. Can't connect to server未处理的承诺拒绝。无法连接到服务器
【发布时间】: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


【解决方案1】:

mongoose.connect 本身(您的 connect 常量)的承诺没有拒绝处理程序。你只使用then,而不是catch,并且你没有将第二个参数提供给then

所以最小的变化是:

connect.then(db => {
    // ...
})
.catch(error => {                            // ***
    // ...handle/report error connecting...  // ***
});                                          // ***

我是否在某处缺少异步函数?

不,但使用一个可能会使代码更容易理解(这是主观的)。 async/await 的目的是让我们可以在使用 Promise 的同时使用我们通常的流控制结构编写代码。

例如,如果您不能使用 top-level await 或者您不想使用,您可以将所有代码包装在立即调用的 async 函数中,如下所示:

const mongoose = require("mongoose");
const Dishes = require("./models/dishes");

const url = "mongodb://localhost:27017/conFusion";

// If you can't use top level `await`, you can use an `async` IIFE
(async () => {
    const connect = await mongoose.connect(url);

    mongoose.set("useUnifiedTopology", true);
    mongoose.set("useNewUrlParser", true);

    console.log("Connected correctly to server");

    var newDish = Dishes({
        name: "Uthappizza",
        description: "test"
    });

    const dish = await newDish.save();
    console.log(dish);
    const dishes = await Dishes.find({});
    console.log(dishes);

    await Dishes.remove({});
    await mongoose.connection.close();
})().catch(error => {
    // ...handle/report error...
});

如果您可以使用 top-level await 并且您愿意(这确实意味着您必须改用 JavaScript's own module syntax 而不是 CJS modules,但恕我直言,无论如何这都是一件好事),您可以这样做:

import mongoose from "mongoose";
import Dishes from "./models/dishes.js";

const url = "mongodb://localhost:27017/conFusion";

try {
    const connect = await mongoose.connect(url);

    mongoose.set("useUnifiedTopology", true);
    mongoose.set("useNewUrlParser", true);

    console.log("Connected correctly to server");

    var newDish = Dishes({
        name: "Uthappizza",
        description: "test"
    });

    const dish = await newDish.save();
    console.log(dish);
    const dishes = await Dishes.find({});
    console.log(dishes);

    await Dishes.remove({});
    await mongoose.connection.close();
} catch (error) {
    // ...handle/report error...
}

但请注意,您可能只想在顶级模块(看起来像这样)中执行此操作,因为它支持模块树的解析。这对于入口点模块或在承诺解决之前无法创建其导出的模块来说很好,但对于您展示的代码中的逻辑,它可能只适用于入口点模块。

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 2019-08-02
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2018-03-31
    • 2023-03-17
    相关资源
    最近更新 更多