一堆查询与动态参数

时间:2017-03-11 12:32:24

标签: javascript mysql node.js asynchronous

首先我从instructions查询

获取一些mysql

获取说明

function getAllInstructions(req,res){
    let mysqlQuery = `SELECT * FROM instructions where id = '` + req.params.id + "'";
    connection.query(mysqlQuery, function(err, rows, fields) {
    if (!err) {
        var instructions = new Array(); // <-- Getting my instructions there
        for (var i=0; i<rows.length;i++) {
             var instruction = new Instruction();
             instruction.id = rows[i].id;
             instruction.title = rows[i].title;
             instructions.push(instruction);
        }
    }
    else {
        console.log('Error while performing Query.');
    } 
});}

每条指令都有自己的steps。 在我完成指令后,我需要为每条指令获得一个steps数组。

正在采取措施的功能

function getStepsForInstruction(_instructionId){
    let mysqlQuery = `SELECT * FROM steps where steps.instruction_id =  '` + _instructionId + "'";
    var steps = [];
    connection.query(mysqlQuery, function(err, rows, fields) {
    if (!err) {
        var steps = [];
        for (var i=0; i<rows.length; i++) {
            var step = new Step();
            step.id = rows[i].id;
            step.title = rows[i].title;
            steps.push(step);
        }
    }
    else {
        console.log('Error while performing Query.');
    }
});}

所以我想做这样的事情

for (var i=0;i<instructions.length;i++) {
     instructions[i].steps = getStepsForInstruction(instructions[i].id);
}

如何使用async或常见?

执行此操作

1 个答案:

答案 0 :(得分:0)

如果让getAllInstructions继续返回没有步骤的指令很重要,我会更改这些函数,以便它们返回promises(并使用正确的参数转义,以及其他一些小问题,如{ {1}}代替[]new Array):

Array#map

...然后使用function getAllInstructions(req, res) { return new Promise(function(resolve, reject) { connection.query('SELECT * FROM instructions where id = ?', [req.params.id], function(err, rows, fields) { if (err) { reject(err); } else { var instructions = rows.map(function(row) { var instruction = new Instruction(); instruction.id = row.id; instruction.title = row.title; return instruction; }); resolve(instructions); } }); }); } function getStepsForInstruction(_instructionId) { return new Promise(function(resolve, reject) { connection.query('SELECT * FROM steps where steps.instruction_id = ?', [_instructionId], function(err, rows, fields) { if (err) { reject(err); } else { var steps = rows.map(function(row) { var step = new Step(); step.id = row.id; step.title = row.title; return step; }); resolve(steps); } }); }); }

Promise.all

但理想情况下,getAllInstructions(req, res).then(function(instructions) { return Promise.all(instructions.map(function(instruction) { return getStepsForInstruction(instruction.id).then(function(steps) { instruction.steps = steps; return instruction; }); }); }).then(function(instructions) { // They're all done, render them here }); 会填写我们的步骤,这简化了事情:

getAllInstructions

请注意,在上文中,我已手动处理为查询创建承诺,但是您可以使用库来实现&#34; promisify&#34;标准的Node风格的回调API,因此您不必手动完成。 (搜索应该为此提供一些选项。)