简体   繁体   English

Nodejs的事件驱动异步回调

[英]Event-driven asynchronous callbacks of Nodejs

I am reading The Node Beginner Book. 我正在阅读节点初学者书。 In the chapter Event-driven asynchronous callbacks, the author gives an example to illustrate the idea of asynchronous callbacks. 在“事件驱动的异步回调”一章中,作者举例说明了异步回调的概念。 The code example is like: 代码示例如下:

var result = database.query("SELECT * FROM hugetable");
console.log("Hello World");

After adding a callback function to database.query, the code becomes asynchronous: 将回调函数添加到database.query后,代码变为异步:

database.query("SELECT * FROM hugetable", function(rows) {
    var result = rows;
});
console.log("Hello World");

My question is why the database.query() function becomes asynchronous simply after adding a callback function. 我的问题是为什么database.query()函数在添加回调函数后变得异步。 I have no experience with Javascript and JQuery before, that might be the reason I cannot understand. 我以前没有Javascript和JQuery的经验,这可能是我无法理解的原因。

There are many functions in node.js that have both an asynchronous flavor and a synchronous flavor. node.js中有许多函数同时具有异步风格和同步风格。 For example, there are two ways to read the contents of a file ( docs ): 例如,有两种方法可以读取文件的内容( docs ):

//asynchronous
fs.readFile("filename.txt", function(err, data) {

});

//synchronous
var data = fs.readFileSync("filename.txt");

The example the author provides does in fact look somewhat confusing, but its possible that the database.query makes an asynchronous call depending on whether a callback is passed in as the second argument. 笔者提供的例子事实上确实看起来有点混乱,但它可能是database.query使得取决于是否异步调用callback传入的第二个参数。

For example, it could be implemented something like this: 例如,它可以实现如下:

function query(queryString, callback) {
  if(callback !== undefined) {
    queryInternal(queryString, callback);
    return;
  }
  else {
    return queryInternalSync(queryString);
  }
}

In general, I think the convention is that a function is either asynchronous or synchronous (not both) so your intuition is right. 一般来说,我认为惯例是functionasynchronoussynchronous (不是两者)所以你的直觉是正确的。

Note that in the synchronous case, console.log will be executed after result has the queried contents whereas in the asynchronous case, console.log will be executed as soon as query function returns and before callback is executed. 请注意,在synchronous情况下,在result具有查询的内容之后将执行console.log而在asynchronous情况下,一旦query函数返回并且在执行callback之前,将执行console.log

Asynchronously means it don't waits for the response and go to the next statements to be executed Asynchronously意味着它不waits response并转到下一个要执行的语句

In your second example the callback function handles your response while executing this, it doesn't waits and console.log("Hello World"); 在您的第二个示例中,回调函数在执行此操作时处理您的响应,它不会等待和console.log("Hello World"); shows the output in console . console显示output

Read this: 读这个:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM