Home > Software engineering >  NodeJS: Promise.resolve returns undefined
NodeJS: Promise.resolve returns undefined

Time:10-23

I am working on Password reset functionality in NodeJS and am facing Promise.resovle undefined issue. I am getting the corrrect values from the database and able to send the actual email, but the promise in the main function doesn't return anything. Any help would be welcome.

Here is my main route function-

router.post('/reset-password', async (req, res) => {
const { email } = req.body
const emailCheck = await db.query('SELECT EXISTS (SELECT email from tickets where email=$1)', [email])
const ifExist = Object.values(emailCheck.rows[0])[0]

if (ifExist) {
    const resetPin = Math.floor(100000   Math.random() * 900000) //random 6 digit pin with 0 not as first digit
    await db.query('UPDATE tickets SET pin=$1 where email=$2', [resetPin, email])
    const result = await emailProcessor(email, resetPin)

    console.log(result) /////returns undefined!

    if (result) {
        return res.status(401).json({
            status: 'success',
            message: 'Pin sent to email if present in our database'
        })
    }
}

res.status(403).json({
    status: 'error',
    message: 'Pin sent to email if present in our database'
})

Here is my helper function using nodemailer-

const transporter = nodemailer.createTransport({
host: 'randomhost',
port: 587,
auth: {
    user: 'abc.email',
    pass: '123'
}})

const sendEmail = (info) => {
return new Promise(async (resolve, reject) => {
    try {
        let result = await transporter.sendMail(info);
        console.log("Message sent: %s", result.messageId);
        console.log("Preview URL: %s", nodemailer.getTestMessageUrl(result));
        resolve(result)
    } catch (error) {
        console.log(error)
    }
})}

const emailProcessor = (email, pin) => {
const info = {
    from: '"app" <email>',
    to: email,
    subject: "Reset Pin",
    text: "Pin is "   pin,
    html: `<b>Reset Pin</b><b>${pin}`,
}
sendEmail(info)}

CodePudding user response:

emailProcessor doesn't currently have a return statement, so it implicitly returns undefined. Change it to:

const emailProcessor = (email, pin) => {
  const info = {
    from: '"app" <email>',
    to: email,
    subject: "Reset Pin",
    text: "Pin is "   pin,
    html: `<b>Reset Pin</b><b>${pin}`,
  };
  return sendEmail(info); // <------ added return
};

P.S, sendEmail does not need to use the promise constructor, new Promise. You're already using promises, so you just need to use the ones that are there, not make a new one.

const sendEmail = async (info) => {
  try {
    let result = await transporter.sendMail(info);
    console.log("Message sent: %s", result.messageId);
    console.log("Preview URL: %s", nodemailer.getTestMessageUrl(result));
    return result;
  } catch (error) {
    console.log(error);
  }
};

  • Related