将异步/等待转换为承诺链接

时间:2019-12-24 08:25:57

标签: javascript promise

我有这段代码,我试图在其中创建一个新用户,对密码进行加密,然后尝试通过mongoose将用户保存在MongoDB中。

有什么方法可以更改异步/等待状态以承诺链接吗?

user = new User({
    name: req.body.name,
    password: req.body.password,
    email: req.body.email
  });
  user.password = await bcrypt.hash(user.password, 10);
  await user.save();

  const token = user.generateAuthToken();
  res.header("x-auth-token", token).send({
    _id: user._id,
    name: user.name,
    email: user.email
  });
});

2 个答案:

答案 0 :(得分:2)

您应该可以执行以下操作:

  user = new User({
    name: req.body.name,
    password: req.body.password,
    email: req.body.email
  });
  bcrypt.hash(user.password, 10)
  .then(pw => { user.password = pw; return user.save(); })
  .then(() => { ...rest of the function here...});

答案 1 :(得分:1)

尝试使用bcrypt salt&hash;

const newUser = new User({
  name,
  email,
  password
});

//Create salt & hash
bcrypt.genSalt(10, (err, salt) => {
  bcrypt.hash(newUser.password, salt, (err, hash) => {
    if (err) throw err;
    newUser.password = hash;
    newUser.save().then(user => {...});
  });
})