node.js - 按时附加事件处理程序 [英] node.js - attaching event handlers on time

查看:55
本文介绍了node.js - 按时附加事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究node.js并在node.js手册中遇到了这个例子:

I'm studying node.js and came across this example in the node.js manual:

...
var req = http.request(options);
req.end();

req.on('upgrade', function(res, socket, upgradeHead) {
  console.log('got upgraded!');
  socket.end();
  process.exit(0);
});
...

我在这个例子中看到的是附加到事件的处理程序HTTP请求,在创建请求之后,甚至之后(计划发送)。更糟糕的是,手册说:

What I see in this example is that handler attached to an event of HTTP request, after the request is created and even after it is (scheduled to be) sent. To make things even worse, manuals says:


如果没有收听此事件,接收升级头的客户端将建立连接关闭。

If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.

事件是否可能发生 req之前.on(... 有机会附加一个处理程序吗?我怀疑我不理解节点的异步模型中的某些东西。或者这个代码来自节点手册,希望网络请求需要的时间比执行下一行代码?!

Isn't it possible for the event to occur before req.on(... had a chance to attach a handler ? I suspect I don't understand something in node's asynchronous model. Or this code from node manual designed in hope that network request will take longer than executing next line of code ?!

另一个例子:

http.get("http://www.google.com/index.html", function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

这里,HTTP请求将在创建对象后立即启动,我们之后才会附加错误处理程序。再次,(1)它是一个co de只有因为
网络延迟才有效,(2)我没有得到关于node.js概念的东西,或者(2b)事件将等待直到我附加一个处理程序?

Here, HTTP request will be initiated immediately after the object created, and we attach an error handler only afterwards. Again, (1) is it a code that works only because of network latencies, (2) I don't get something about node.js concepts, or (2b) event will "wait" until I attach a handler to it ?

编辑
更好的例子,也来自手动。下面的 Bad 示例之所以不同,只是因为在好的情况下,我们足够快地附加事件,因此低机会会错过数据,或者这种方式永远不可能错过数据(为什么?!)

EDIT: Even better example, also from manual. Good and Bad examples below are different only because in the good one we attach the event quick enough and thus have low chances to miss data, or it is never possible to miss data this way (and why ?!)

// Good
request.on('response', function (response) {
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

// Bad - misses all or part of the body
request.on('response', function (response) {
  setTimeout(function () {
    response.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
    });
  }, 10);
});


推荐答案

你想念的是JavaScript不是异步的所有!我的意思是JavaScript是单线程的,异步操作实际上并不是异步的。有一个非常奇特的队列模型,它给出了JavaScript异步的错觉(不要误解我: 是最有效的模型)。

What you miss is that JavaScript isn't asynchronous at all! What I mean is that JavaScript is single-threaded and asynchronous operations are actually not asynochronous. There is a very fancy queue model which gives as the illusion of JavaScript being asynchronous (don't get me wrong: it still is the most efficient model).

那是什么意思?这意味着一旦同步代码运行,就不可能其他代码并行运行。例如,在此代码中

So what does it mean? It means that once the synchronous code is running it is impossible for other code to be running parallely. So for example in this code

var req = http.request(options);
req.end();
req.on(...);

请求已安排,但主线程(即操作)尚未以<$结束C $ C> req.end()。只要主操作没有完成,就不会发生异步代码。特别是在实际事件发生之前,处理程序始终设置。

the request is scheduled, but the main thread (i.e. the operation) hasn't ended at req.end(). As long as the main operation has not finished no asynchronous code can fire in-between. In particular the handler is always set before the actual event has any chance to occure.

还有一个例子可以让它更清晰一些。请考虑以下代码:

One more example to make it a bit clearer. Consider this code:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
    while(true) { } // <------ infinite loop doing nothing
}).listen(1337, '127.0.0.1');

请注意,第一个请求将成功完成。但任何其他请求永远不会得到回复。这是因为循环永远不会完成操作,而JavaScript 不能跳转到另一个事件。这段代码永远崩溃了应用程序,超出了任何希望。所以要小心使用Node.js的同步代码。 :)

Note that the first request will finish with success. But any other request will never get a response. This is because the loop will never finish the operation and JavaScript cannot jump to another event because of it. This code permamently crashes the app beyond any hope. So be careful with synchronous code with Node.js. :)

这篇关于node.js - 按时附加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆