【问题标题】:How to get rid of UnhandledPromiseRejectionWarning in Node Mongo Express Application如何摆脱 Node Mongo Express 应用程序中的 UnhandledPromiseRejectionWarning
【发布时间】:2020-10-17 06:39:08
【问题描述】:

您好!

我有一个 Node-Express 端点,它调用 addAdminController.js(附在下面)来创建一个新的管理员。

从功能的角度来看,一切都很好。但是,当您使用 mongoose FindOne 方法检查用户是否已经存在时,它会在控制台上留下警告。但是,这并不会停止该函数的运行,并且我在 Postman 中成功地将“电子邮件已在使用中”作为 json 对象返回。

我想知道为什么我会看到这个错误,以及我在处理 Promise 时做错了什么。非常感谢您的帮助。

addAdminController.js

const adminsModel = require("../../../../models/admins");
const bcrypt = require("bcryptjs");

exports.addAdminController = async (req, res, next) => {
    const { name, email, password, role, image, status } = req.body;

    //check if user already exists
    try {
        adminsModel
            .findOne({ email }, (err, admin) => {
                if (admin) {
                    res.status(400).json("Email Already in use");
                    return;
                }
            })
            .exec();
    } catch (error) {
        return res.status(500).json("Something Went Wrong");
    }

    //Encrypt Password using Bcrypt
    const saltRounds = 12;
    const hashPass = bcrypt.hashSync(password, saltRounds);

    //Create New Model with Hashed Password
    const newAdmin = new adminsModel({
        name: name,
        email: email,
        password: hashPass,
        role: role,
        image: image,
        status: status,
    });

    // Save new admin user.
    try {
        await newAdmin.save();
        res.json(newAdmin);
        return;
    } catch (error) {
        res.status(400).json("There was an error creating admin user");
    }
};

控制台警告

node:18700) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:533:11)
    at ServerResponse.header (F:07_Developrs\Github\APIv2\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (F:07_Developrs\Github\APIv2\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (F:\07_Developrs\Github\APIv2\node_modules\express\lib\response.js:267:15)
    at exports.addAdminController (F:\07_Developrs\Github\APIv2\routes\api\admins\addAdmin\addAdmin.controller.js:37:19)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18700) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:18700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

【问题讨论】:

    标签: node.js mongodb express ecmascript-6 async-await


    【解决方案1】:

    首先,您不应该使用findOne 函数的回调版本,因为findOne 函数调用下面的代码将在findOne 的回调执行之前执行。

    由于findOne函数调用下面的代码取决于用户是否已经存在,awaitadminsModel.findOne(...)的结果并检查findOne函数是否返回了用户。

    其次,用try-catch 块包装findOne 函数调用以处理被拒绝的承诺。

    try {
         const user = await adminsModel.findOne({ email });
         
         if (user) {
            return res.status(400).json("Email Already in use");
         }
         
         // code to run if user doesn't exists
    
    } catch (error) {
        return res.status(500).json("Something Went Wrong");
    } 
    

    【讨论】:

    • 嗨,我试过了,但又出现了同样的错误。我更新了上面的代码以在 try-catch 中显示 findOne。
    猜你喜欢
    • 2019-02-22
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    相关资源
    最近更新 更多