0

I am developing an application using NodeJS where two queries depend on each other here is explanation of my situation.

I have to query database for some values say A then I have to query database for some other value B only if there is an A in the database.

I know I can do this in NodeJS' natural way like execute query for A when its result is ready execute query for B in A's callback and then finally render response in B's callback.

Here is my question, is there a design issue in the solution I just mentioned perhaps about nested callbacks.

Second is there any method in which I can make NodeJs IO as Blocking from NON-Blocking?

user2009750
  • 3,169
  • 5
  • 35
  • 58
  • If you do blocking IO, your entire program will be unable to respond to any requests at all until those queries complete. That is not usually what you want. – Chuck Mar 04 '14 at 07:54
  • Node does have some I/O functions that offer both blocking and non-blocking versions - such as fs.readFile and fs.readFileSync. If your database driver offers a blocking function - you could use that. One example of when blocking might be desired is when the node app starts - since you won't be taking any requests until the initialization functions complete anyway. – Svbaker Mar 04 '14 at 12:26

2 Answers2

2

I was made aware of a library called Async Which i wish id found when i started my NodeJs projects. It can take care of this and much more.

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

basic example from site that would help in your scenario

async.series([
    function(callback){
        // do db call one
        callback(null, 'one');
    },
    function(callback){
        // do db call two
        callback(null, 'two');
    }
],
function(err, results){
    // results is now equal to ['one', 'two']
}); 
ste2425
  • 4,656
  • 2
  • 22
  • 37
1

Here is my question, is there a design issue in the solution I just mentioned perhaps about nested callbacks.

No, your solution is perfectly fine.

Second is there any method in which I can make NodeJs IO as Blocking from NON-Blocking?

Yes. You can write your own c++ extension to provide blocking calls.

alex
  • 11,935
  • 3
  • 30
  • 42