2

可能重复:
使用 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  + ';');
...

谢谢, 考菲

4

1 回答 1

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) {
        ....
 }

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

于 2012-08-06T17:59:56.210 回答