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))…”?
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,
existsis asynchronous (non-blocking), it doesn’t have a return value and instead calls a callback when it’s done.existsSyncis synchronous (blocking); it returns its result rather than having a callback.If
testis your own function, and it only calls synchronous functions, then it’s synchronous: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:Instead, you have to provide a callback: