节点callback触发在同一时间

考虑一下 :

一次只能有一个callback点火

所以考虑这个代码:

var http = require("http"); function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); 

如果我的应用程序收到请求,则调用OnRequest。 如果一次只能触发一个回叫,那么请求就会排队。 这样对吗?

Node.js被devise成当请求到达时给予callback函数的信息并让它处理它,主进程等待下一个请求。

所以如果你在onRequest中设置setTimeout为10秒。 并作出100请求服务器的所有请求将返回数据10秒后不10,20,30 … … –

由于node.js是单进程应用程序,所以请求将排队,但是只有很less的时间。 您可以尝试使用实验性function,例如http://nodejs.org/api/cluster.html来并行处理请求。 这里的排队并不意味着除非reques1得到回答,否则request2将不会被回答,但这意味着节点进程将会询问他们,直到每个先前的请求得到他们的callback指派,不影响你的网站的performance。

阅读http://book.mixu.net/node/single.html它是最棒的书之一也http://www.nodebeginner.org/

编辑1 Node.js请求你写非阻塞代码。 如果没有阻止代码,我们使用callback。

Node.js是单线程应用程序,但它的行为像一个主要的重要线程和其他不太重要的线程池(没有特定的优先级)。

 Eg: An ambulance waits for phone call to come every time. when it gets a call it goes to pick up the patient and take him to the hospital. while the doctor is performing operation on the patients. Ambulance team does not switch off their phone and wait for its first patient to get healthy but If they get another call they go to pick up the next guy when they were off to receive next guy hospital calls and say first patient is healthy and drop him home, ambulance does not leave other guy in pain but complete its second task and then drop first guy home. so callback was doctorPerformOperation which was put in thread pool and recieveTheGuy was a blocking operation 

所以从你的代码来看,它是非常小的,所以可能会发生每个响应都可能在请求之后,但也可能是在2nds连接的最后一个“ack”之前,5个(几乎)同时请求3被获取callback。

更具体的例子

阻止代码

  setTimeout(function() { console.log('bye') }, 100); while(1) { } 

“再见”将永远不会被打印

无阻塞代码

  setTimeout(function() { console.log('bye') }, 100); setInterval(function() { console.log('hi'); }, 100); 

再见.1秒后将被打印,但如果您喜欢在相同的情况下打印,则可以延迟几秒。

主进程空闲时执行callback。

更多的非阻塞

 setTimeout(function() { console.log('bye') }, 100); setInterval(function() { console.log('hi'); }, 50); setInterval(function(){ console.log('hello'); },100); 

猜猜,这会发生什么?

编辑2:

我写了一个小代码

 exports.sample = function (res) { var tcpsocket = net.createConnection(port, host); tcpsocket.on('connect', function () { tcpsocket.write('query'); console.log('tcp'); }); tcpsocket.on('data', function (data) { res.write(data); }); tcpsocket.on('end', function () { console.log('end'); res.end(); }); tcpsocket.on('error', function (e) { var ret={error:'error'} res.end(JSON.stringify(ret)); console.log('Error occured in tcp socket'); console.log(e); }); tcpsocket.on('close', function () { console.log('socket close'); res.end(); }); }; 

现在我连接到的sockets是10秒内以10秒为间隔写入数据的交streamsockets。 所以每个请求大约需要100秒才能完成。 因为我没有在“data”事件中调用res.end,浏览器不加载任何东西,直到完成完整的请求。 如果你想看到实时发送的数据,你可以使用curl来获取相同的url。

结果:当您同时打开10个选项卡时,您将能够在100秒内(不是100秒,200秒…)