我创建了一个需要一系列员工的函数。我需要找出mysql中不同表上的每个员工的教育详细信息,并将其附加到特定的Employee对象。
这里是员工对象的样子:
employee: {
id: 1,
name: 'John'
}
这是我写的功能:
const getEducationDetails = (employees, done) => {
var empArr = [];
employees.forEach(employee => {
empArr.push(employee);
employee.education = [];
const sql = `SELECT * FROM employee_education_details
WHERE employee_id = "${employee.id}"`
db.query(sql, (err, educationDetails, fields) => {
employee.education.push(educationDetails);
});
});
return done(empArr);
}
因此,我创建了一个自定义的empArr数组,并将每个员工对象推送到该数组中。为了存储教育细节,我创建了员工[' education']。由于nodejs的非阻塞I / O技术,出现了这个问题。
节点没有等待mysql查询完成,因此甚至在将教育细节插入其中之前就返回了empArr。
我试图找出解决此问题的最佳方法。
答案 0 :(得分:0)
您可能想要使用Promises
。您可以使用promises
执行此操作,如下所示:
const getEducationDetails = (employees, done) => {
var empPromArr = [];
employees.forEach(employee => {
let p = new Promise((resolve, reject) => {
empArr.push(employee);
employee.education = [];
let empEduPromises = [];
empEduPromises.push(query(employee));
Promise.all(empEduPromises).then(educationDetails => {
employee.education = educationDetails;
resolve(employee)
}, err => {
reject(err);
});
});
empPromArr.push(p);
});
Promise.all(empPromArr).then(empArr => {
return done(empArr);
}, err => {
//error handling
});
}
function query(employee) {
return new Promise((resolve, reject) => {
const sql = `SELECT * FROM employee_education_details
WHERE employee_id = "${employee.id}"`
db.query(sql, (err, educationDetails, fields) => {
if (err) {
reject(err);
}
else {
resolve(educationDetails);
}
});
});
}