[英]cannot response.write on connection node.js
I wrote this code in node.js : 我在node.js中编写了这段代码:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('start\n');
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'hostname',
user : 'user',
password : 'pass',
database : 'dbname',
});
connection.connect();
connection.query('SELECT code FROM user_type', function(err, rows, fields) {
if (err) throw err;
//This for is to run on all the results
for(var i=0;i<2;i++){
res.write('name:',rows[i].code);
}
});
connection.end();
res.end('End');
}).listen(8080);
console.log('Server running');
my questions are: 1. why did the res.write in the for loop print nothing in my html page? 我的问题是:1.为什么在for循环中的res.write在我的html页面中什么都不显示? 2. what to write instead of 2 in the for?
2.写什么而不是for中的2?
The issue is the timing of execution. 问题是执行的时机。
Since connection.query()
is asynchronous, it delays the execution of the callback function
to when the query finishes, but allows the surrounding block of code to continue in the meantime. 由于
connection.query()
是异步的,因此它将回调function
的执行延迟到查询结束时执行,但同时允许周围的代码块继续进行。 This results in res.end('End')
being executed before res.write('name:',rows[i].code)
. 这导致
res.end('End')
在res.write('name:',rows[i].code)
res.end('End')
之前执行。
To also delay res.end()
, move it inside the callback: 要同时延迟
res.end()
,请将其移到回调中:
connection.query(..., function(err, rows, fields) { if (err) throw err; for (...) { res.write('name:',rows[i].code); } res.end('End'); });
rows
should be an Array
when there isn't an err
, so you can use its length
property : 没有
err
, rows
应该是一个Array
,所以可以使用它的length
属性 :
for (var i = 0; i < rows.length; i++) {
It's also a common practice to store the value of length
in a local variable: 将
length
的值存储在局部变量中也是一种常见的做法:
for (var i = 0, len = rows.length; i < len; i++) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.