Edit: We can close. Isn't truly asynchronous, non-blocking javascript impossible?
var PATH = require ("path");
var URL = require ("url");
var sleep = function (ms){
var start = new Date ().getTime ();
while ((new Date ().getTime () - start) < ms);
}
require ("http").createServer (function (req, res){
if (URL.parse (req.url).pathname === "/1"){
console.log ("tab 1: I'm in");
PATH.exists ("test", function (exists){
sleep (5000);
res.writeHead (200, {"Content-Type": "text/plain"});
res.end ("1");
console.log ("tab 1: I'm done");
});
}else{
console.log ("tab 2: I'm in");
res.writeHead (200, {"Content-Type": "text/plain"});
res.end ("2");
console.log ("tab 2: I'm done");
}
}).listen (80);
- Copy the content into a file.
- Execute the file.
- Open a new tab in browser. Set the url to
localhost/1. Don’t go yet. - Open a new tab in browser. Set the url to
localhost/2. Don’t go yet. - Go back to the first tab. Press enter and immediately after change to the second tab and press enter.
Result:
-
console log:
tab 1: I’m in
tab 1: I’m done
tab 2: I’m in
tab 2: I’m done -
Tab 1 waits 5 seconds to receive the result “1”.
- Tab 2 also has to wait 5 seconds because tab 1 is sleeping for 5 seconds.
The docs says that all is asynchronous except the code. Only one thread. Only one request at a time. Requests are enqueued.
I/O calls are supposed to be asynchronous, right? Then why tab 2 has to wait to tab 1 if the callback comes from an asynchronous I/O process?
Thanks.
Because your
sleepis blocking the event loop.Replace it with
setTimemout(function() { /* Code to run */ }, 5000);and watch/2respond immediately.The actual I/O is asynchronous, but all actions you’re performing on the I/O happen in the event loop. If something is blocking the event loop, everything else has to wait, just like you said.
EDIT. For more clarity, look at the following ASCII graphic:
Basically, only one at a time for each thread. Because the first request handler blocks for 5 seconds (and it’s essentially impossible to beat your filesystem with your fingers in a speed test), the second response doesn’t even start to be handled until the first request is almost done.