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

3
  • 1
    maybe you should look into Async.js github.com/caolan/async Commented Aug 6, 2012 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? Commented Aug 6, 2012 at 17:49
  • yes, if we can do these requests without nesting, that should be better. Commented Aug 7, 2012 at 5:22

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Even with these functions you should be doing callbacks for the other functions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.