Search code examples
javascriptnode.jsblockingnonblocking

blocking IO in nodejs


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?


Solution

  • 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']
    });