mysql - multiple nested callback functions before parent's callback in javascript -


im using expressjs , mysql package. have user table, each user have many skills, projects, certifications stored in different tables. how can of these data single user object.

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 user obj         // main problem        //get skills , projects.... , asign user obj       parsearraydata(skillsql, user.id, skill, function (skills) {           user.skills = skills;         }       );       parsearraydata(projectsql, user.id, project, function (project) {           user.projects = projects;         }       );       // 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 = [];       (var = 0; < rows.length; i++) {         array[i] = new obj(rows[i]); // map obj's attributes fields       };       callback(rows);     }   });        }; 

you might have these different tables names (assume): users, skills, projects, certifications;

function result db query;

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

function fetch results user id , return json object;

 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 result.                    id: userid,                    users: users,                    projects: projects,                    skills: skills,                    certifications: certifications                 };                 callback(result);              });            });        });     });     callback(null);  }); 

usage:

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

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -