const con = require("../../database/connection").getConObject();
let member = [];
function getStudent(id, callback) {
return new Promise(function (resolve, reject) {
const getGroupDetails =
"SELECT g.id,s.username,s.name FROM group_list as g LEFT JOIN student_registration as s on s.id = g.id WHERE g.groupID = ?";
con.query(getGroupDetails, id, (err, results) => {
results.forEach((temp) => {
member.push({ usernames: temp.username, name: temp.name });
});
callback(id);
member = [];
});
resolve(1);
});
}
let mergedResult = [];
function addStudent(id) {
mergedResult.push({ id: id, members: member });
}
function getLastRecord() {
return new Promise(function (resolve, reject) {
const getGroupID = "SELECT groupID FROM group_list GROUP BY groupID;";
con.query(getGroupID, (err, result) => {
if (result && result.length > 0) {
result.forEach((element) => {
getStudent(element.groupID, addStudent);
});
}
});
resolve(1);
});
}
exports.getGroupDetails = (req, res) => {
try {
getLastRecord().then((value) => {
res.status(200).json({ msg: mergedResult });
mergedResult = [];
});
} catch (err) {
console.log(err);
res.status(500).json({ msg: "Something is wrong" });
}
};
我想在从数据库成功获取所有数据并且合并结果数组不为空时发送合并结果。但有时我得到空结果,有时我得到一半数据,有时是完美的或有时是冗余数据。请帮我解决这个问题,我无法追踪承诺电话。如果承诺不可能,请给我一些解决方法
您的服务器具有全局变量
member
和 mergedResult
,所有传入请求同时使用它们。这是行不通的,一个请求将覆盖并发请求刚刚写入的内容,导致像您观察到的那样不可预测的结果。
不要使用全局变量,而是使用请求局部变量,例如
req.member
和 req.mergedResult
。要在函数中访问这些内容,请将它们 req
作为附加参数传递,例如,
getLastRecord(req).then((value) => {...});