Nodejs 和非阻塞噩梦
我目前正在使用 node.js 和 MySQL 开发 API。我对这种非阻塞的东西很陌生,我有一个问题。我正在使用节点和 MySQL 模块。
假设我们有一个这样的函数:
function doQuery(sql, callback) {
connect(); //does the Client.connect()
client.query(sql, function(err, results, fields) {
if (err) {
errorLog.trace(err, __filename);
throw err;
} else {
logger.trace('DATABASE ACCESS: {query: ' + sql + '} result: OK', __filename);
}
client.end();
callback(results);
});
}
一切运行正常,回调处理值的返回,但有一些事情困扰着我。我的浏览器直到响应返回为止,我不知道这是否是因为在此期间节点实际上被阻止了。
那么,我如何知道某个操作是否确实阻塞了我的节点进程?我认为当您将回调传递给函数时,节点会自动处理它并将该回调的执行放入事件循环的队列中。但我实际上不确定这
一切对你来说有意义吗?
I'm currently developing an API using node.js and MySQL. I'm new to this non-blocking stuff, and I have a question. I'm using node and MySQL module.
Say that we have a function like this:
function doQuery(sql, callback) {
connect(); //does the Client.connect()
client.query(sql, function(err, results, fields) {
if (err) {
errorLog.trace(err, __filename);
throw err;
} else {
logger.trace('DATABASE ACCESS: {query: ' + sql + '} result: OK', __filename);
}
client.end();
callback(results);
});
}
Everything runs ok, callback handles the return of the values, but there's something that bothers me. My browser what till the response is back and i don't know if this is because during this time node is actually blocked, or not.
So, how can I know if an operation is actually blocking my node process? I thought that when you pass a callback to a function, node automatically handles it and puts the execution of this callback at the queue of the event loop. But I'm not actually sure about that
Does all this make any sense to you?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
浏览器等待和 Node.js 阻塞是有区别的。
浏览器必须等待,因为它无法立即取回数据。一旦您发回响应,浏览器将停止等待。仅仅因为浏览器正在等待并不意味着 Node.js 正在阻塞。这只是意味着连接仍然打开,
Node.js 在等待回调时处于空闲状态。它不会阻塞。
Node.js 可以与浏览器客户端建立数千个开放连接。这并不意味着它会阻塞每一个。它只是意味着在有回调要处理或有新请求要处理之前处于空闲状态。
There is a difference between the browser waiting and node.js blocking.
The browser has to wait because it can't get the data back instantly. The browser will stop waiting once you send the response back. Just because the browser is waiting doesn't mean that node.js is blocking. It just means that the connection is still open
Node.js idles whilst your waiting for the callback. it does not block.
node.js can have thousands of open connections with browsers clients. This does not mean it's blocking on each one. It simply means that is idling until it has a callback to handle or a new request to handle.