我尝试了两个代码。我只是同时从两个浏览器访问这些程序。为什么在Node.js上表示“连续”处理http请求?
在Sample1中,res.send在所有处理之后执行并且是通用实现。 我的意思是,这些“setTimeout”可以是数据库访问或类似的东西。
在Sample2中,首先执行res.send,然后执行其余的处理。
根据Sample1的输出,每个http请求都被串行处理。所以如果有人同时访问这个网站,他们需要等待每个以前的人。首先,我认为原因是因为Node.js连续处理所有内容。但是根据Sample2的结果,我发现这是错误的理解。 从结果中,Node.js可以同时处理一些函数,包括像setTimeout这样的非阻塞代码。
所以我不明白为什么表达是这样实现的。 因此,我们需要使用像PM2一样的Cluster来同时处理一些http请求。
你能教我为什么表达这样的行为?同时处理一些http请求的唯一解决方案就是使用Cluster?
的Sample1
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var id = Math.floor(1000*Math.random())
console.log('0 - ' + id)
setTimeout(()=>{
console.log('1 - ' + id)
setTimeout(()=>{
console.log('2 - ' + id)
setTimeout(()=>{
console.log('3 - ' + id)
res.send('Hello World!');
}, 1000)
}, 1000)
}, 1000)
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
的Sample1的输出
0 - 957
1 - 957
2 - 957
3 - 957
0 - 447
1 - 447
2 - 447
3 - 447
样品2
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
var id = Math.floor(1000*Math.random())
console.log('0 - ' + id)
setTimeout(()=>{
console.log('1 - ' + id)
setTimeout(()=>{
console.log('2 - ' + id)
setTimeout(()=>{
console.log('3 - ' + id)
}, 1000)
}, 1000)
}, 1000)
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
样品2
的输出0 - 902
0 - 742
1 - 902
1 - 742
2 - 902
2 - 742
3 - 902
3 - 742
Sample2似乎与Sample1完全相同的代码? – DAXaholic
非常抱歉!我修好了它。 – ykensuke9
增加超时时你会得到不同的结果吗? – eenagy