简体   繁体   English

不确定Node.js代码是否异步

[英]Not sure if Node.js code is asynchronous

I'm running a simple node.js application that sends a JSON object upon http post. 我正在运行一个简单的node.js应用程序,该应用程序在http发布时发送JSON对象。 The application is using node-mysql and express modules. 该应用程序正在使用node-mysql和express模块​​。

Here is the code. 这是代码。

HTML: HTML:

$(document).ready(function () {
  setInterval(function() {
    var path = window.location.pathname;
    $.ajax({
      url: path,
      type: "POST",
      contentType: "application/json",
      processData: false,
      complete: function (data) {
        var a = JSON.parse(data.responseText);
        var display = "<ul style='list-style-type:none'>";
        var count = 1;
        for (var key in a) {
          if (a.hasOwnProperty(key)) {
            var str = a[key].split('|');
            display += "<li style='background: #333; margin: 10px 0;'>" + str[0] + " <span style='color:#ddd;'>to " + str[1] + "</span></li>";
            count++;
          }
        }
        display += "</ul>"
        $('#output').html(display);
      }
    });
  }, 3000);
});

Page configuration: 页面配置:

app.get('/', function(req,res) {
  res.sendfile(__dirname + '/index.html');
});

app.get('/docs', function(req,res) {
  res.sendfile(__dirname + '/display.html');
});

app.get('/bio', function(req,res) {
  res.sendfile(__dirname + '/display.html');
});

app.get('/int', function(req,res) {
  res.sendfile(__dirname + '/display.html');
});

And one of the app.post methods used to send the JSON object upon page request. 和app.post方法之一,用于在页面请求时发送JSON对象。 There are four, the root, which is just a list of links pointing to /docs, /bio, and /int. 根有四个,它是指向/ docs,/ bio和/ int的链接的列表。

app.post('/docs', function(req, res){
  var query = "/* query */";
  connection.query(query, req.body, function(err, rows, fields) {
    if (err) throw err;
    var obj = {};
    var id = "";
    for (var i = 0; i < rows.length; i++) {
      id = "id" + i;
      obj[prop] = rows[i].name + '|' + rows[i].counter_name;
    }
    res.send(JSON.stringify(obj));
  });
});

The application runs and seems to update fine, but I'm not sure if it is asynchronous or not. 该应用程序可以运行,并且似乎可以正常更新,但是我不确定它是否异步。 Basically, just need to know if it is, and if it isn't some pointers to make it so. 基本上,只需要知道它是否是,是否不是要这样做的一些指针即可。

Rule of thumb in node: unless the word "sync" occurs in the method name, all IO is asynchronous. 节点中的经验法则:除非方法名称中出现单词“ sync”,否则所有 IO都是异步的。 This is essentially the point of node. 这本质上就是节点。

IO includes any time a file must be opened, which includes all connections, including HTTP connections, SQL connections, RabbitMQ connections, etc., and all files on disk, including log files, etc. IO包括必须打开文件的任何时间,包括所有连接,包括HTTP连接,SQL连接,RabbitMQ连接等,以及磁盘上的所有文件,包括日志文件等。

Typically to understand asynchronous code you should look for where the callbacks are. 通常,要了解异步代码,您应该寻找回调的位置。 In Javascript callbacks are very often given as anonymous functions. 在Javascript中,回调函数通常以匿名函数的形式给出。 eg 例如

connection.query(query, req.body, function(err, rows, fields) {
//                                 ^ anonymous function definition

The last argument is a callback. 最后一个参数是回调。 In general I would define a callback as a function that is passed as an argument to another function (often, but not always, as an anonymous function.) When that whole line of code is executed, the callback is of course not called. 通常,我将回调定义为一个函数,该函数作为参数传递给另一个函数(通常但不总是作为匿名函数)。当执行全部代码行时,当然不会调用该回调。 It's called when the definition of query says to call it, which in this case will mean after the response to the query is received, which can be seconds later, and in particular long after the following code is executed, and in a call stack far away. query定义说要调用它时调用它,在这种情况下,这意味着在收到查询响应之后,可能是几秒钟之后,尤其是在执行以下代码后很长时间,并且在调用堆栈中远。

Callbacks are needed to achieve asynchrony because right after the connection.query is called, the response hasn't come in yet. 需要回调来实现异步,因为在connection.query调用之后,响应尚未进入。 So it's impossible to do anything with the response, whether it's an error or rows. 因此,无论是错误还是行,都无法对响应做任何事情。 That needs to happen later, ie asynchronously. 这需要稍后进行,即异步进行。 So you pass a callback to do that handling at some later point. 因此,您传递回调以在以后的某个时间进行该处理。

Peppering your code with console.log is a quick and dirty way to demonstrate that some function is running asynchronously: console.log标记代码是一种快速而肮脏的方法,用于演示某些函数正在异步运行:

console.log("before");
someFunction(param1, function() {
    console.log("inside");
});
console.log("after");

If the function executes asynchronously, then you'll see something like this: 如果该函数异步执行,那么您将看到以下内容:

before
after
inside

It's not necessarily true that a function passed to another function as a callback will run asynchronously, but it's often the case. 一个函数作为回调传递给另一个函数并不一定要异步运行,但通常是这样。 The only way to know for sure is to read the documentation or, better yet, test it. 唯一可以确定的方法是阅读文档,或者更好地进行测试。

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

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