The novice understanding of Node is that if I re-write synchronous, or in-line code, to utilize functions / callbacks, I can ensure that my code is non-blocking. I'm curious how this works in terms of the event stack. The simple example from here: Don't understand the callback - Stackoverflow is that this will block:
var post = db.query("select * from posts where id = 1");
doSomethingWithPost(post)
doSomethingElse();
While this wont:
callback = function(post){
doSomethingWithPost(post)
}
db.query("select * from posts where id = 1",callback);
doSomethingElse();
Ok, I understand that we should use callbacks. But in terms of the event stack why does this work? Javascript is single threaded.. in the first example line one makes use of an expensive and blocking I/O operation. Line 2 can't execute till line one is done. Is this because line 2 requires information from line 1? Or is it because I/O events are just fundamentally blocking operations meaning that they seize control and don't give it back until done...
In the second example the expensive I/O has been moved into a function, and we now have a callback function. Certainly the callback can't execute until the I/O is done.. This would not change. So the difference in amount of time it takes to execute between one and two must primarily be what would happen if a second request hit the server.
If a second request hit example one, it wouldn't be able to process until request 1 was done because of the blocking operation.. but in the example two.. does moving operations into functions automatically spawn child processes or act as multi-threaded? If Javscript is single threaded this would still pose a problem unless there was some way of doing parallel processing.. Does a function / callback only guarantee to be non-blocking IF we make use of non-blocking techniques like child processes, etc...