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

前端 未结 3 2022
生来不讨喜
生来不讨喜 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.

提交回复
热议问题