Search code examples
node.jsexpressnode-mysql

how to get the final results in nodejs mysql mutli sql query


how i can get the final results gracefully except using asyncjs.

current code is not graceful, any othe method ?

thanks a lot.

exports.index = function(req, res){
    connection.query('select * from ued_task where taskState=0 and isQ=0 order by taskId desc', function(err, tasks, fields) {
        tasks.forEach(function(task, index){
            task.userIds = (task['UD']+task['UI']+task['builder']).replace(/\,+/g,',').replace(/\,$/, '').split(',');
            task.users = [];
            task.userIds.forEach(function(single) {
                connection.query("select * from user where userId=" + single, function(err, rows, fields) {
                    task.users.push({
                        'name' : rows[0].name,
                        'ename' : rows[0].userName,
                        'position' : rows[0].position
                    });
                    if(index === tasks.length-1){
                        if (err) throw err;
                        console.log(tasks);
                        res.render('index', { 
                            title: 'task sys',
                            tasks: tasks,
                            moment: moment
                        });
                    }
                });
            });
        });
    });
};

Solution

  • exports.index = function(req, res){
    
        var result = {};
        result.title = 'task sys';
        result.moment = moment;
    
        var f3 = function(single){
    
            connection.query("select * from user where userId=" + single, function(err, rows, fields) {
                task.users.push({
                    'name' : rows[0].name,
                    'ename' : rows[0].userName,
                    'position' : rows[0].position
                });
                if(index === tasks.length-1){
                    if (err) throw err;
                    console.log(tasks);
                    res.render('index', result);
                }
            });
    
        }
    
        var f2 = function(task, index){
            task.userIds = (task['UD']+task['UI']+task['builder']).replace(/\,+/g,',').replace(/\,$/, '').split(',');
            task.users = [];
            task.userIds.forEach(f3);
        }
    
        var f1 = function(cb){
            var sql = 'select * from ued_task where taskState=0 and isQ=0 order by taskId desc'
            connection.query(sql, function(err, tasks, fields) {
                result.tasks = tasks;
                tasks.forEach(f2);
            }); 
        };
    
        f1();
    
    };
    

    i have been edited