函数将对象作为 promise { pending } 返回

问题描述

我们使用 Twilio API 发送短信,然后自定义函数验证 OTP。我们希望使用强文本唯一电话号码登录用户的凭据是我们的主要功能

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

这是我们获取用户对象的驱动程序函数,其中包含我们传递给 res.send 的所有凭据,而 res.send 返回空对象。 当我们在主有效函数中记录对象时,其记录为 promise { pending }

解决方法

您正在混合使用回调和异步。继续第二个:

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) {

    // ...

  }
};

编辑:

你如何记录函数调用?使用 await