首页 > 解决方案 > node.js异步多个等待不适用于用户注册

问题描述

我正在尝试使用 async/await 重现此代码,但我不知道如何

.then.catch 链/巢

exports.signup = (req, res, next) => {
  bcrypt.hash(req.body.password, 10)
    .then(hash => {
      const user = new User({
        email: req.body.email,
        password: hash
      });
      user.save()
        .then(() => res.status(201).json({ message: 'Utilisateur créé !' }))
        .catch(error => res.status(400).json({ error }));
    })
    .catch(error => res.status(500).json({ error }));
};

我想出尝试使用 async/await

exports.signup = async (req, res, next) => {
    try {
       const hash = await bcrypt.hash(req.body.password, 10);
       const user = new User({
           email: req.body.email,
           password: hash
       });
       console.log(user);
       let saveUser = await user.save();
       console.log(saveUser);
       res.status(201).json({ message: 'Utilisateur créé !'})
    } catch (e) {
        res.status(500).json({e})
    }
};

我在控制台中获取用户,但代码在 user.save() 期间崩溃,因为我没有从 console.log(saveUser) 得到任何东西

我一直在阅读您可以将 await 函数堆叠到一个 try 块中,但也许在这里它不起作用,因为您需要

我试过分离 try/catch,要求我在 try 块之外初始化哈希,因为我将在第二次尝试中使用它,但它也不起作用。

按照 Nil Alfasir 的想法编辑后:

exports.signup = async (req, res, next) => {
    try {
       const hash = await bcrypt.hash(req.body.password, 10);
       const user = new User({
           email: req.body.email,
           password: hash
       });
       console.log(user);
       user.save();
       return res.status(201).json({ message: 'Utilisateur créé !'})
    } catch (e) {
        return res.status(500).json({e})
    }
};

但我在控制台中得到了这个

(node:43390) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: myFirstDatabase.users index: username_1 dup key: { username: null }
.
.
.
(node:43390) 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(). (rejection id: 1)
(node:43390) [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.jsexpressasync-await

解决方案


在保存异步时更正 Nir ​​Alfasi

  1. save()一个异步函数SAVE ASYNC

所以它不会返回任何东西。

如果有错误可以被捕获。


推荐阅读