Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't understand the callback and non-blocking example - Node.js

Tags:

node.js

In the book Hands-on node, the author gives an example of blocking I\O,

var post = db.query("select * from posts where id = 1");
doSomethingWithPost(post)
doSomethingElse();

The author says nothing is executed till line 1 is finished executing db query

And, then he shows non-blocking code

callback = function(post){
doSomethingWithPost(post)
}

db.query("select * from posts where id = 1",callback);
doSomethingElse();

Isn't this also blocking till the query is executed?

So, doSomethingElse won't be executed till query is completed.

like image 298
ruskin Avatar asked Jul 11 '11 04:07

ruskin


2 Answers

You should always read non-blocking functions like doRealStuff( params, callback ) as "put doRealStuff, params and callback in the queue, do callback() when reached queue end". This also may help avoid doing mistakes like

for (var i=0; i < 1000000; i++)
{
    // I want to do many http requests now
    do_request(test_url);
}

// not a single byte is sent here because event loop was blocked by for loop
like image 126
Andrey Sidorov Avatar answered Nov 15 '22 07:11

Andrey Sidorov


The author is absolutely correct. If the second example is non-blocking, the code execution will trigger the query and then continue executing the rest of the code. The callback function will be called after the query is complete, at some undetermined point in the future. doSomethingElse(); will be called immediately.

What actually makes this example blocking vs non-blocking is not clear in the examples you have provided. It will be something internal to the DB implementation. Perhaps by passing in a callback parameter you are indicating that the request should be non-blocking.

Hopefully that helps, tyler.

like image 36
Tyler Egeto Avatar answered Nov 15 '22 08:11

Tyler Egeto