使用 Moongose 在 Node.js 中处理一系列 then() 块以进行重定向

问题描述 投票:0回答:1

我有以下代码,但收到一条错误消息,指出我正在尝试在发送重定向后修改标头。我认为这是我处理 if 语句和返回的方式。我修改了代码,现在重定向可以工作,但我认为我误解了逻辑。请参阅此处的第一个代码:

exports.postSignup = (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  const confirmPassword = req.body.confirmPassword;
  // check if user exist
  User.findOne({ emailAddress: email })
    .then((user) => {
      if (user) {
        console.log("user exists please log in!");
        return res.redirect("/auth/login");
      }
      const newUser = new User({
        emailAddress: email,
        password: password,
        cart: {
          products: [],
        },
      });
      return newUser.save();
    })
    .then((result) => {
        console.log("added user");
        res.redirect("/auth/login");
    })
    .catch((e) => {
      console.log(e);
      throw e;
    });
};

有效的固定版本:

exports.postSignup = (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  const confirmPassword = req.body.confirmPassword;
  // check if user exist
  User.findOne({ emailAddress: email })
    .then((user) => {
      if (user) {
        console.log("user exists please log in!");
        return res.redirect("/auth/login");
      }
      const newUser = new User({
        emailAddress: email,
        password: password,
        cart: {
          products: [],
        },
      });
      return newUser.save();
    })
    .then((result) => {
      // this makes the redirect only if the user is created
      if (result) {
        console.log("added user");
        res.redirect("/auth/login");
      }
    })
    .catch((e) => {
      console.log(e);
      throw e;
    });
};

有人可以帮我找出为什么早期版本不起作用吗?我只能想象我调用了两次redirect()。

node.js express mongoose
1个回答
0
投票

根据文档

猫鼬查询不是承诺。查询是 thenables,这意味着它们有一个用于 async/await 的 .then() 方法,以方便使用

我建议采用

async/await
模式,您可以在 docs 中阅读该模式,但请注意:

不同 Mongoose 方法的具体实现值有所不同,并且可能会受到配置的影响。具体方法请参考API文档。

在代码的这一部分中:

if (user) {
   console.log("user exists please log in!");
   return res.redirect("/auth/login");
}

您正在将

res.redirect
返回到下一个
then()
链。然后您再次拨打
res.redirect

但是在这部分代码中:

return newUser.save();

您正在从已解决的 Promise 返回结果,因为

save()
方法是异步的。

使用

async/await
会喜欢这样:

exports.postSignup = async (req, res) => { //< mark function as async
    try{
        const email = req.body.email;
        const password = req.body.password;
        const confirmPassword = req.body.confirmPassword;
        const user = await User.findOne({ emailAddress: email }); //< use await keyword
        if(user){
            console.log("user exists please log in!");
            return res.redirect("/auth/login"); //< early return
        }else{
            const newUser = new User({
                emailAddress: email,
                password: password,
                cart: {
                    products: [],
                },
            });
            await newUser.save(); //< use await keyword
            console.log("added user");
            res.redirect("/auth/login");
        }
    }catch(e){
        console.log(e);
        // handle err
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.