如何在node.js中执行同步SQL查询

时间:2012-08-06 17:16:23

标签: javascript mysql node.js

  

可能重复:
  Synchronous database queries with Node.js

通常,我们执行SQL查询并在回调中获取结果。像这样:

sqlExec('SELECT COL FROM TBL;', function (err, results, fields) {
    doSomething(results);
});

但是如果我们需要用SQL结果做更复杂的工作,那么代码会更加丑陋,就像这样:

var tmp = '';
sqlExec('SELECT COL1 FROM TBL1;', function (err, results, fields) {
    tmp = doSomething(results);
    sqlExec('SELECT COL2 FROM TBL2 WHERE CONDITION2 = ' + tmp +  ';', function (err, results, fields) {
        tmp = doSomething2(results);
        sqlExec('SELECT COL3 FROM TBL3 WHERE CONDITION3 = ' + tmp  + ';', function (err, results, fields) {
            ....
        });
    });
});

我们有想法让它同步吗?像这样:

var tmp = '', result = ''; 
result = sqlExec('SELECT COL1 FROM TBL1;');
tmp = doSomething(result);
sqlExec('SELECT COL2 FROM TBL2 WHERE CONDITION2 = ' + tmp  + ';');
tmp = doSomething(result);
sqlExec('SELECT COL3 FROM TBL3 WHERE CONDITION3 = ' + tmp  + ';');
...

谢谢, Gcaufy

1 个答案:

答案 0 :(得分:1)

这里描述了一个很好的模式http://stella.laurenzo.org/2011/03/bulletproof-node-js-coding/第2段, 你的例子就是这样的:

sqlExec('SELECT COL1 FROM TBL1;', function (err, results, fields) {
    var tmp = doSomething(results);
    nextStep( tmp );
}

function nextStep( tmp ) {
    sqlExec('SELECT COL2 FROM TBL2 WHERE CONDITION2 = ' + tmp +  ';', function (err, results, fields) {
    var othertmp = doSomething2(results);
    nextNextStep( othertmp );
    }
}

function nextNextStep( tmp ) {
    sqlExec('SELECT COL3 FROM TBL3 WHERE CONDITION3 = ' + tmp  + ';', function (err, results, fields) {
        ....
 }

现在它几乎看起来像你想要的结果