People sometimes refer the callback pattern below being asynchronous.
function beAsync(msg, cb){
cb(msg);
}
beAsync("a", function(msg){
console.log(msg);
});
console.log("b");
What people sometime say is that beAsync allows for the rest of the code to run then the callback happens when it’s ready.
When I call beAsync and real asynchronous functions like fs.readFile initially there must be some code that runs synchronously and then something happens that allows the code after readFile rest of the code is allowed is allowed to run.
Am I correct in saying something representing the callback enters a loop at a lower level than JavaScript?
So a revision to beAsync would include a setTimeout.
function beAsync(msg, cb){
setTimeout( function(){ cb(msg) }, 1);
}
So setTimeout and the internals of readFile can speak to a layer which JavaScript sits on?
Speaking to this lower layer is the only way to achieve non-blocking code in JavaScript?
That is kind of correct. Node is just one part of the equation. The framework itself makes heavy use of threads to manage things that can block, like IO. Look at
http://www.quora.com/How-does-IO-concurrency-work-in-node-js-despite-the-whole-app-running-in-a-single-thread
That’s not very detailed, but it correct from a high level. Whenever you fire off some asynchronous work, and give the method a callback, there is work done to execute your callback with the result of the work.