Using mongoose promises with async/await

前端 未结 5 450
谎友^
谎友^ 2020-12-13 13:19

I\'m trying to get the hang of using Mongoose promises with the async/await functionality of Node.js. When my function printEmployees is called I want to save t

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 14:14

    if you're going to use async/await then it works like this.

    • await in front of the function that returns a promise.
    • async in front of the wrapping function.
    • wrap the function body inside try/catch block.

    Please have a look on this function, it is a middleware before i execute a specific route in express.

    const validateUserInDB = async (req, res, next) => {
        try {
            const user = await UserModel.findById(req.user._id);
            if (!user) return res.status(401).json({ message: "Unauthorized." });
            req.user = user;
            return next();
        } catch (error) {
            return res.status(500).json({ message: "Internal server error." })
        }
    }
    
    • The code after await is waiting the promise to be resolved.
    • Catch block catches any error happened inside the try block even if the error that is triggered by catch method comes from awaiting promise.

提交回复
热议问题