function returns object as promise { pending }

Viewed 93

we are using Twilio API to send SMS and then the custom function verifies the OTP. We want the credential of the user who has logged in with a strong textunique phone number here is our main function.

const donorLogin = (req, res) => {
donorCredentials
 .findOne({ mobileNo: req.body.phone })
 .then((user) => {
   if (!user) {
     return res.status(401).json({
       success: false,
       msg: There is no account of ${req.body.phone},
     });
   }

   // Function defined at bottom of app.js
   const isValid = validPassword(req.body.password, user.hash, user.salt);

   if (isValid) {

     const accessToken = jwt.sign(
       {
         mobileNo: user.mobileNo,
       },
       JWT_AUTH_TOKEN,
       {
         expiresIn: "1d",
       }
     );

     res
       .status(200)
       
       .send(getUser(req.body.phone));
   } else {
     res.status(401).json({ success: false, msg: "Wrong Password" });
   }
 })
 .catch((err) => {
   res.status(400).send({ err: err });
 });
};

async function getUser(phone) {
  try {
    const userInfo= await Donor.find({ mobileNo: phone });
    // console.log(userInfo[0]);
    // let data = userInfo[0];
    return JSON.stringify(userInfo[0]) ;
  }
  catch (err) {
    console.log(err);
    res.status(500).send(err);
  }
};

This is the driver function where we are getting the user object with all the credential which we are passing to res.send which is returning null object. when we log the object in the main valid function its logs as promise { pending }

1 Answers

You are mixing callbacks and async. Go with the second:

const donorLogin = async (req, res) => {
  try {
    // await added, no callback
    const user = await donorCredentials.findOne({ mobileNo: req.body.phone });

    if (!user) {
      return res.status(401).json({
        success: false,
        msg: There is no account of ${req.body.phone},
      });
    }

    const isValid = validPassword(req.body.password, user.hash, user.salt);

    if (isValid) {
      const accessToken = jwt.sign({ mobileNo: user.mobileNo }, JWT_AUTH_TOKEN, { expiresIn: "1d" });

      // await added
      res.status(200).send(await getUser(req.body.phone));
    } else {

      // ...

    }
  } catch (e) {

    // ...

  }
};

Edit:

How do you log the function call? Using await?

Related