gpt4 book ai didi

mysql - javascript中父级回调之前的多个嵌套回调函数

转载 作者:行者123 更新时间:2023-11-29 20:57:43 25 4
gpt4 key购买 nike

我正在使用expressjs和mysql包。我有一个用户表,每个用户可以有许多技能、项目、认证存储在不同的表中。如何将所有这些数据放入单个用户对象中。

getUserDataById(req.params.id, function (user) {
if (user) {
res.send(user);
}
}
var getUserDataById = function (id, callback) {
connection.query(userSql, id, function (err, rows) {
if (rows[0]) {
user = new User(rows[0]); //parse row data to user obj
// The main problem
//get skills and projects.... and asign to user obj
parseArrayData(skillSql, user.id, Skill, function (skills) {
user.skills = skills;
}
);
parseArrayData(projectSql, user.id, Project, function (project) {
user.projects = projects;
}
);
// is here
callback(user);
}
});
}
var parseArrayData = function (query, id, Obj, callback) {
connection.pool.query(query, id, function (err, rows) {
if (err) {
throw err;
} else {
console.log('rows',rows);
var array = [];
for (var i = 0; i < rows.length; i++) {
array[i] = new Obj(rows[i]); // map obj's attributes with fields
};
callback(rows);
}
});
};

最佳答案

您可能有这些不同的表,其名称(假设):用户技能项目认证 ;

从数据库获取结果进行查询的函数;

function executeQuery(tablename, userId, callback) {
var sql = 'select * from ' + tablename + ' where id = ' + userId;
connection.query(sql, function (err, rows) {
if (err) { callback(err, null); }
else { callback(null, rows); }
})
}

获取用户 ID 的所有结果并返回 json 对象的函数;

 var getUserDataById = function (userId, callback) {
executeQuery('users', userId, function(users) {
executeQuery('projects', userId, function(projects) {
executeQuery('skills', userId, function(skills) {
executeQuery('certifications', userId, function(certifications) {
var result = { // format you result.
id: userId,
users: users,
projects: projects,
skills: skills,
certifications: certifications
};
callback(result);
});
});
});
});
callback(null);
});

用法:

getUserDataById(req.params.id, function (user) {
if (user) {
res.send(user);
}
}

关于mysql - javascript中父级回调之前的多个嵌套回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37498862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com