Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Does Node.js really do the background I/O tasks asynchronously?

Does Node.js really do the background I/O tasks asynchronously?

Problem

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) 
  1. Copy the content into a file.
  2. Execute the file.
  3. Open a new tab in browser. Set the url to localhost/1. Don't go yet.
  4. Open a new tab in browser. Set the url to localhost/2. Don't go yet.
  5. 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.

Problem courtesy of: Gabriel Llamas

Solution

Because your sleep is blocking the event loop.

Replace it with setTimemout(function() { /* Code to run */ }, 5000); and watch /2 respond 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:

Event Loop Thread: ------+req1HandlerExistsCall+-------+req1Wait5Sec++++++++++++++++++++++++++req2ExistsCall+-------+req2Immediate+-------------
         HTTP I/O: -+req1+--------------------------------------+req2+--------------------------------------+req1Response+--------+req2Response+
         File I/O: ----------------------------+exists1+----------------------------------------------------+exists2+---------------------------

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.

Solution courtesy of: David Ellis

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Does Node.js really do the background I/O tasks asynchronously?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×