首页 > 解决方案 > 如何摆脱 Node Mongo Express 应用程序中的 UnhandledPromiseRejectionWarning

问题描述

问候!

我有一个 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.jsmongodbexpressecmascript-6async-await

解决方案


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

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

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

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");
} 

推荐阅读