node.js程序执行的模糊流程

时间:2014-02-21 10:57:45

标签: javascript node.js

请找到以下代码,

我在代码中仍然无法理解的是,为什么浏览器在执行下一个查询之前会等待10秒钟。它不应该只是将睡眠查询传递给数据库,然后继续立即执行下一个吗?

var http = require('http');
var mysql = require('mysql');

http.createServer(function (request, response) {

var connection = mysql.createConnection({

    host: 'localhost',
    user: 'root',
    password: '',
    database: 'pops',    
    dateStrings: 'true',
    multipleStatements: 'true'
});

// Connect to MySQL (if there is an error, report it and terminate the request)
connection.connect (function (err) {
    // connected! (unless `err` is set)

    if (err !== null)
    {
        console.log('Error '+err.code);
    }
    else
    {
        console.log('Connection to database successful!');
    }
});

 connection.query("SELECT sleep(10);", function(err, rows) {

        // There was a error or not?
        if (err !== null)
        {
            console.log("Query Rrror:" + err);
        }
        else
        {
            // Shows the result on console window              
              console.log("called after 10 seconds");              
        } 
 });

 connection.query("SELECT * FROM team", function(error, result) {

        // There was a error or not?
        if (error !== null)
        {
            console.log("Query Rrror:" + error);
        }
        else
        {
            // Shows the result on console window
              response.writeHead(200, {"Content-Type": "text/html"});
              length = result.length - 1;

              for(var i = 0; i <= length; i++)
              {
                  row_obj = result[i];

                  team_id = row_obj.id;
                  team_name = row_obj.team_name;
                  team_color = row_obj.color;
                  created_at = row_obj.created_at;

                  response.write('Team ID: ' + team_id + '<br />');
                  response.write('Team Name: ' + team_name + '<br />');
                  response.write('Team Color: ' + team_color + '<br />');
                  response.write('Creation Date: ' + created_at + '<br />');
                  response.write('<br /><br />');
              }

              response.end("OK");
        } 
 });

 // Close connection
 connection.end();

 }).listen(8080, "127.0.0.1");

1 个答案:

答案 0 :(得分:0)

首先,您应该在httpRequest处理程序之外创建mysql连接。

是的,Node.JS将在不等待的情况下执行这两个查询,但我认为正在发生的是,node-mysql正在对查询进行排队。