简体   繁体   中英

i want to reset password with token but => SyntaxError: await is only valid in async function

i want to send mail using sendgrid and nodemailer but => SyntaxError: await is only valid in async function

help me how to solve this error

`

const postReset = async (req, res, next) => {
  //generate random token
 crypto.randomBytes(32, (err, buffer) => {
    if (err) {
      console.log(err);
      return res.redirect('/reset');
    }
  const token = buffer.toString('hex');
  const user = await User.findOne({ email: req.body.email });
  try {
    user.resetToken = token;
    user.resetTokenExpiration = Date.now() + 3600000;
    //save updated user
    const result = await user.save();
    if (result) {
      res.redirect('/');
      await transporter.sendMail({
        to: req.body.email,
        from: 'Yo-books@yogi.com',
        subject: 'Password reset',
        html: `
            <p>You requested a password reset</p>
            <p>Click this <a href="http://localhost:3000/reset/${token}">link</a> to set a new password.</p>,
      });
    }
  } catch (error) {
    req.flash('error', 'No account with that email found.');
    return res.redirect('/reset');
  }
})
};
`

Add async keyword in the parent function, which in this case is callback of crypto.randomBytes . Your code should look like:

const postReset = async (req, res, next) => {
  //generate random token
 crypto.randomBytes(32, async (err, buffer) => {

    // ...

      await transporter.sendMail({

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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