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

前端 未结 3 2021
生来不讨喜
生来不讨喜 2021-01-02 23:59

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)         


        
相关标签:
3条回答
  • 2021-01-03 00:31

    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.

    0 讨论(0)
  • 2021-01-03 00:40

    Ryan Dahl's intro is a pretty good overview, but this beginner's tutorial is excellent, it explains in detail and in a friendly way the premise of non/blocking operations in Javascript (and so Node).

    But in a nutshell, the callback parameter in the 2nd example you've posted isn't executed until db.query finishes, it is "held on to for later", which means code after the db.query() call can continue to be executed.

    0 讨论(0)
  • 2021-01-03 00:41

    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
    
    0 讨论(0)
提交回复
热议问题