mysql - NodeJS with MySQL - Return blank Array
问题描述
I have initialized an array "userTasklist". I have pushed the object in this array in .map function. After .map, I have console this Array but array is blank.
Than I have console the object in .map function and all the value print successfully but in Array there are no value. Don't know why.
exports.allUserList = (req, res) => {
let userID = req.params.userid;
const ghusersQuery = "SELECT user_id, name, employee_code FROM users WHERE under_gh = ?";
conn.query(ghusersQuery, [userID], (err, userdata) => {
if (err) {
res.send({ message: err })
} else {
if (userdata && userdata.length > 0) {
let userTasklist = [];
userdata.map((datauser) => {
var objtask = {};
const userDataQuery = "SELECT * FROM tasklist WHERE user_id = ?";
conn.query(userDataQuery, [datauser.user_id], (errnew, taskdata) => {
if (taskdata && taskdata.length > 0) {
objtask = {
userid: datauser.user_id,
tasklist: taskdata
}
userTasklist.push(objtask);
}
})
})
console.log(userTasklist)
res.send({ message: "user list fetched", userdata: userdata, tasklistdata: userTasklist })
} else {
res.send({ message: "Data not found!" })
}
}
})
}
解决方案
使用mysql21将查询作为 Promise 处理的简化解决方案。
exports.allUserList = async (req, res) => {
const { userid } = req.params
const users = await connection.query('SELECT user_id, name, employee_code FROM users WHERE under_gh = ?', [userid])
if (!users.length)
return res.send({ message: "Data not found!" })
// better fetch all relevant tasks in bulk
const tasks = await connection.query('SELECT * FROM tasklist WHERE user_id IN (?)', [users.map(r => r.user_id)])
res.send({ message: "user list fetched", users, tasks })
}
推荐阅读
- anylogic - 如何减少我使用的源块的数量?
- c# - 获取 Vuforia 目标图像旋转度数
- django - 如何根据当前用户是否是博客帖子的所有者来限制模板中显示的编辑链接?
- automation - 使用 JXA 向新联系人添加电子邮件
- android - Android Studio Emulator 目录已移除
- android - 如何在 Android Studio 中找到最新版本的 Kotlin
- ios - AppDelegate swfit4.2中的“applicationDidReceiveMemoryWarning”内存警告警报?
- c# - 将日期值 YYYY-MM-DD 从 excel 表导入 DataTable 仅获取最后一个值 DD
- r - 在汽车库中使用 scatterplotMatrix 时,右上角的绘图和左下角的绘图有什么区别?
- mongodb - 将日期转换为时间戳 mongodb