Reputation: 3156
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))..."?
Upvotes: 1
Views: 332
Reputation: 1074295
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) {
// ...
}
});
Upvotes: 8
Reputation: 25456
The blocking/non-blocking terminology is a bit confusing here, I would say 'all functions in Node.JS are blocking and all IO in node standard library is non-blocking, except when indicated explicitly by Sync suffix in function name'.
Upvotes: 0
Reputation: 3951
Yes, this code is synchronous executed and "blocking". But console.log will be executed every time the script runs because you only omitting the document.write in the if statement.
Upvotes: 0