我正在使用nodeJs Express,并且我有一个在另一个函数中使用的异步函数。
这是我的代码:
/* get user info */
const getUserInfo = async (req) => {
let userID = req.cookies.userId;
if(!userID) return null;
await connection.query('SELECT * FROM users WHERE id = ' + userID,
function (err, rows, fields) {
if (err) throw err
// if user not found
if (rows.length === 0) {
return null;
}
// if user found
else {
return rows[0];
}
});
}
/* display dashboard page */
router.get("/", async function (req, res, next) {
let userInfo = await getUserInfo(req);
console.log(userInfo) // It's result is undefined
if (userInfo) {
res.render('dashboard/profile', {
fullName: userInfo.fname + " " + userInfo.lname,
email: userInfo.email,
phone: userInfo.phone,
});
}
else {
res.render('authentication/register', {
title: 'ثبت نام',
});
}
});
如何解决这个问题?我需要 userInfo 给我返回一些数据。
最佳答案
await
仅当右侧的值是一个 promise 时才有用。
connection.query
正在接受回调函数,这意味着它不会返回 promise 。
您需要:
- 了解如何使您正在使用的 API 返回 promise (如果可能)
- Wrap the callback in a promise
- 将 API 替换为原生支持 Promise 的 API
您还需要 getUserInfo
拥有自己的 return
语句。
关于javascript - JS 异步函数返回未定义,尽管在异步函数内调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72075348/