首页 > 解决方案 > 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!" })
            }
        }
    })
}

标签: mysqlnode.jsarrays

解决方案


使用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 })
}

推荐阅读