如何解决函数将对象作为 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
?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。