简体   繁体   English

将 async/await 转换为 promise 链接

[英]Converting async/await to promise chaining

I have this snippet of code, where I am trying to create a new user, bcrypt the password and trying to save the user in the MongoDB through mongoose.我有这段代码,我试图在其中创建一个新用户,对密码进行 bcrypt,并尝试通过 mongoose 将用户保存在 MongoDB 中。

Is there any way I can change this async/await to promise chaining?有什么办法可以改变这个异步/等待承诺链接?

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

You should be able to do something like this:你应该能够做这样的事情:

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

Try this, with bcrypt salt & hash;试试这个,用 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 => {...});
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM