2

Possible Duplicate:
Synchronous database queries with Node.js

Usually, we execute a SQL query and get the result in a callback. like this:

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

But if we need to do more complicated job with the SQL results, the code will be more uglier, like this:

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

Do we have a idea to make it sync? like this:

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  + ';');
...

Thanks, Gcaufy

Community
  • 1
  • 1
Gcaufy
  • 148
  • 1
  • 8
  • 1
    maybe you should look into Async.js https://github.com/caolan/async/ – Roest Aug 06 '12 at 17:18
  • It looks like the main thing that you're struggling with is chaining the async requests to be a little more manageable without all the nesting, right? – jcolebrand Aug 06 '12 at 17:49
  • yes, if we can do these requests without nesting, that should be better. – Gcaufy Aug 07 '12 at 05:22

1 Answers1

1

A nice pattern is described here http://stella.laurenzo.org/2011/03/bulletproof-node-js-coding/ paragraph 2, with your example it would be something like this:

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

now it almost looks like your desired result

Roest
  • 826
  • 6
  • 16