Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Is "if ( somefunction( ) )" blocking in node.js?

Is "if ( somefunction( ) )" blocking in node.js?

Problem

test = function(x){   
    if ( some conditions ) { return true; }
    else { return false; }
}


if (test(y)) {document.write("You have done this before!")​}​;​

console.log("Checked!");

The intention is to check if the user performed some action in the past. These are just mock up codes that do not really reflect what I am actually doing though.

Question:

I am relatively new to node.js so please forgive me if this sounds trivial. Suppose test(y) is true. Can I be sure that the console.log will be executed after the document.write? Even if test(y) takes a long time to run?

In other words, I need "if (test(y))..." to be Blocking. I understand that passing a Function as an argument, e.g. setInterval(test(y),100); can be async and non-blocking. But what about "if(test(y))..."?

Problem courtesy of: Legendre

Solution

NodeJS has both synchronous (blocking) and asynchronous (non-blocking) functions. (More accurately: The functions themselves are always "blocking" but a whole class of them start something that will complete later and then return immediately, not waiting for the thing to finish. Those are what I mean by "non-blocking.")

The default in most cases is asynchronous (and they accept a callback they call when the thing they've started is done); the synchronous ones tend to have names ending in Sync.

So for example, exists is asynchronous (non-blocking), it doesn't have a return value and instead calls a callback when it's done. existsSync is synchronous (blocking); it returns its result rather than having a callback.

If test is your own function, and it only calls synchronous functions, then it's synchronous:

function test(x) { // Obviously a nonsense example, as it just replicates `existsSync`
    if (existsSync(x)) {
        // The file exists
        return true;
    }
    return false;
}

// This works
if (test("foo.txt")) {
    // ...
}

If it calls an asynchronous function, it's asynchronous, and so it can't return a result via a return value that can be tested by if:

// WRONG, always returns `undefined`
function test(x) {
    var retVal;

    exists(x, function(flag) {
        retVal = flag;
    });

    return retVal;
}

Instead, you have to provide a callback:

function test(x, callback) {

    exists(x, function(flag) {
        callback(flag);
    });
}

// This works
test("foo.txt", function(flag) {
    if (flag) {
        // ...
    }
});
Solution courtesy of: T.J. Crowder

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Is "if ( somefunction( ) )" blocking in node.js?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×