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